<template>
  <div class="tenant">
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        :selectConfig="selectConfig"
        highlight-current-row
        @get-list="getList">
        <template #code="{ item }">
          <div style="width: 100%">
            <a style="color: #409eff; cursor: pointer; word-break: break-all" @click="pushProcessApproval(item)">{{ item.code }}</a>
          </div>
        </template>
        <template #amount="{ item }">
          <div>
            <span style="padding-right: 4px">{{ item.currency }}</span>
            <span>{{ moneyFormat(item.amount, 2) }}</span>
          </div>
        </template>
        <template #sellCorporationName="{ item }">
          <div>
            <span v-if="item.sellCorporationName">{{ item.sellCorporationName }}</span>
            <span v-else>{{ item.oldSellCorporationName }}</span>
          </div>
        </template>
        <template #buyCorporationName="{ item }">
          <div>
            <span v-if="item.buyCorporationName">{{ item.buyCorporationName }}</span>
            <span v-else>{{ item.oldBuyCorporationName }}</span>
          </div>
        </template>
      </byTable>
    </div>

    <el-dialog title="打印" v-if="openPrint" v-model="openPrint" width="860">
      <div id="printMe">
        <div id="pdfDom" style="width: 800px; padding: 16px; font-size: 12px !important">
          <div style="font-size: 18px; text-align: center">
            {{ printDetails.sellCorporationNameEn }}
          </div>
          <div style="text-align: center">
            {{ printDetails.sellCountryName }},{{ printDetails.sellProvinceName }},{{ printDetails.sellCityName }},{{ printDetails.sellDetailedAddress }}
          </div>
          <div style="font-size: 14px; color: #409eff; text-align: center; padding-top: 16px">PROFORMA INVOICE</div>
          <div style="padding-top: 8px">
            <div>PI NO. : {{ printDetails.contractCode }}</div>
            <div>PI DATE: {{ printDetails.createTimeEn }}</div>
          </div>
          <div style="border: 1px solid black; display: flex">
            <div style="width: 50%; border-right: 1px solid black">
              <div style="color: #409eff">VENDOR:</div>
              <div>{{ printDetails.sellCorporationNameEn }}</div>
              <div style="padding: 16px 0">
                {{ printDetails.sellCountryName }},{{ printDetails.sellProvinceName }},{{ printDetails.sellCityName }},{{ printDetails.sellDetailedAddress }}
              </div>
              <div>CONTACT: {{ printDetails.sellContactName }}</div>
              <div>TEL.: {{ printDetails.sellContactNumber }}</div>
            </div>
            <div style="width: 50%">
              <div style="color: #409eff">BUYER:</div>
              <div>{{ printDetails.buyCorporationName }}</div>
              <div style="padding: 16px 0">
                {{ printDetails.buyDetailedAddress }},{{ printDetails.buyCityName }},{{ printDetails.buyProvinceName }},{{ printDetails.buyCountryName }}
              </div>
              <div>CONTACT: {{ printDetails.buyContactName }}</div>
              <div>TEL.: {{ printDetails.buyContactNumber }}</div>
            </div>
          </div>
          <div style="height: 16px"></div>
          <div style="border: 1px solid black">
            <div style="display: flex; width: 100%">
              <div style="width: 33%; border-bottom: 1px solid black; border-right: 1px solid black">
                <div style="color: #409eff">COUNTRY OF ORIGIN:</div>
                <div>{{ printDetails.sellCountryName }}</div>
              </div>
              <div style="width: 34%; border-bottom: 1px solid black; border-right: 1px solid black">
                <div style="color: #409eff">COUNTRY OF DESTINATION:</div>
                <div>{{ printDetails.buyCountryName }}</div>
              </div>
              <div style="width: 33%; border-bottom: 1px solid black">
                <div style="color: #409eff">PLACE OF DISCHARGE:</div>
                <div>{{ printDetails.transportRemark }}</div>
              </div>
            </div>
            <div style="display: flex; width: 100%">
              <div style="width: 33%; border-bottom: 1px solid black; border-right: 1px solid black">
                <div style="color: #409eff">TERMS OF DELIVERY:</div>
                <div>
                  {{ dictValueLabel(printDetails.tradeMethods, tradeMethods) }}
                </div>
              </div>
              <div style="width: 34%; border-bottom: 1px solid black; border-right: 1px solid black">
                <div style="color: #409eff">CURRENCY:</div>
                <div>
                  {{ printDetails.currency }}
                </div>
              </div>
              <div style="width: 33%; border-bottom: 1px solid black">
                <div style="color: #409eff">EXPORT BY/VIA:</div>
                <div>
                  {{ dictValueLabel(printDetails.transportMethod, shippingMethod) }}
                </div>
              </div>
            </div>
            <div style="display: flex; width: 100%">
              <div style="width: 33%; border-right: 1px solid black">
                <div style="color: #409eff">DELIVERY TIME:</div>
                <div>{{ printDetails.deliveryTime }}</div>
              </div>
              <div style="width: 67%">
                <div style="color: #409eff">TERMS OF PAYMENT:</div>
                <div>{{ printDetails.remark }}</div>
              </div>
            </div>
          </div>
          <div style="height: 16px"></div>
          <div class="baseRow" style="display: flex; color: #409eff">
            <div class="contentRow" style="width: 50px; text-align: center">NO.</div>
            <div class="contentRow" style="width: calc(100% - 450px); text-align: center">COMMODITY, SPECIFICATION</div>
            <div class="contentRow" style="width: 100px; text-align: center">UNIT</div>
            <div class="contentRow" style="width: 100px; text-align: center">QUANTITY</div>
            <div class="contentRow" style="width: 100px; text-align: center">UNIT PRICE</div>
            <div class="contentRow" style="width: 100px; text-align: center">TOTAL PRICE</div>
          </div>
          <div v-if="printDetails.productInfoList && printDetails.productInfoList.length > 0">
            <div class="baseRow" style="display: flex" v-for="(item, index) in printDetails.productInfoList" :key="item.productId">
              <div class="contentRow" style="width: 50px; text-align: center">
                {{ index + 1 }}
              </div>
              <div class="contentRow" style="width: calc(100% - 450px); text-align: center">
                {{ item.productName }}
              </div>
              <div class="contentRow" style="width: 100px; text-align: center">
                {{ dictValueLabel(item.productUnit, productUnit) }}
              </div>
              <div class="contentRow" style="width: 100px; text-align: center">
                {{ item.productQuantity }}
              </div>
              <div class="contentRow" style="width: 100px; text-align: center">
                {{ item.productPrice }}
              </div>
              <div class="contentRow" style="width: 100px; text-align: center">
                {{ item.amount }}
              </div>
            </div>
          </div>
          <div class="baseRow" style="display: flex; color: #409eff">
            <div class="contentRow" style="width: calc(100% - 400px); text-align: center">SUBTOTAL:</div>
            <div class="contentRow" style="width: 100px; text-align: center"></div>
            <div class="contentRow" style="width: 100px; text-align: center">
              {{ statistics("productQuantity", 0) }}
            </div>
            <div class="contentRow" style="width: 100px; text-align: center"></div>
            <div class="contentRow" style="width: 100px; text-align: center">
              {{ statistics("amount", 2) }}
            </div>
          </div>
          <div class="baseRow" style="display: flex">
            <div class="contentRow" style="width: calc(100% - 100px); text-align: right; color: #409eff">FREIGHT COST:</div>
            <div class="contentRow" style="width: 100px; text-align: center">
              {{ statisticsTwo("amount", 2) }}
            </div>
          </div>
          <div class="baseRow" style="display: flex">
            <div class="contentRow" style="width: calc(100% - 100px); text-align: right; color: #409eff">TOTAL PRICE:</div>
            <div class="contentRow" style="width: 100px; text-align: center">
              {{ printDetails.totalAmount }}
            </div>
          </div>
          <div class="baseRow" style="display: flex; border-bottom: 1px solid black">
            <div class="contentRow" style="width: 100%">
              {{ translateIntoEnglish(printDetails.totalAmount, printDetails.currency) }}
            </div>
          </div>
          <div style="height: 16px"></div>
          <div class="baseRow" style="color: #409eff">
            <div class="contentRow" style="width: 100%">ACCOUNT INFORMATION:</div>
          </div>
          <div class="baseRow" style="border-bottom: 1px solid black">
            <div class="contentRow" style="width: 100%">
              <div style="line-height: 24px; padding-left: 4px; word-break: break-all; word-wrap: break-word">
                Beneficiary Name: {{ printDetails.beneficiaryName }}
              </div>
              <div style="line-height: 24px; padding-left: 4px; word-break: break-all; word-wrap: break-word">
                Beneficiary Bank: {{ printDetails.beneficiaryBank }}
              </div>
              <div style="line-height: 24px; padding-left: 4px; word-break: break-all; word-wrap: break-word">
                Beneficiary Bank Address: {{ printDetails.beneficiaryBankAddress }}
              </div>
              <div style="line-height: 24px; padding-left: 4px; word-break: break-all; word-wrap: break-word">
                Beneficiary Account Number: {{ printDetails.beneficiaryAccountNumber }}
              </div>
              <div style="line-height: 24px; padding-left: 4px; word-break: break-all; word-wrap: break-word">Swift Code: {{ printDetails.swiftCode }}</div>
              <div style="line-height: 24px; padding-left: 4px; word-break: break-all; word-wrap: break-word">
                Beneficiary Address: {{ printDetails.beneficiaryAddress }}
              </div>
            </div>
          </div>
          <div style="height: 32px"></div>
          <div style="display: flex">
            <div style="width: 50%">
              <div style="color: #409eff">CONFIRMED BY VENDOR:</div>
              <div>{{ printDetails.sellCorporationNameEn }}</div>
            </div>
            <div style="width: 50%">
              <div style="color: #409eff">CONFIRMED BY BUYER:</div>
              <div>{{ printDetails.buyCorporationName }}</div>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="openPrint = false" size="large">取消</el-button>
        <el-button v-print="printObj" size="large">打印</el-button>
        <el-button type="primary" @click="clickDownload()" size="large">下载PDF</el-button>
      </template>
    </el-dialog>

    <el-dialog title="编辑" v-if="openUpdate" v-model="openUpdate" width="500">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="update">
        <template #sellContactName>
          <div style="width: 100%">
            <el-autocomplete
              v-model="formData.data.sellContactName"
              :fetch-suggestions="querySearchSellPerson"
              clearable
              class="inline-input w-50"
              placeholder="请输入联系人"
              @select="handleSellPerson">
            </el-autocomplete>
          </div>
        </template>
        <template #buyContactName>
          <div style="width: 100%">
            <el-autocomplete
              v-model="formData.data.buyContactName"
              :fetch-suggestions="querySearchBuyPerson"
              clearable
              class="inline-input w-50"
              placeholder="请输入联系人"
              @select="handleBuyPerson">
            </el-autocomplete>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="openUpdate = false" size="large">取 消</el-button>
        <el-button type="primary" @click="clickSubmit()" size="large">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import byTable from "@/components/byTable/index";
import { ElMessage } from "element-plus";
import byForm from "@/components/byForm/index";

const { proxy } = getCurrentInstance();
const tradeMethods = ref([]);
const corporationList = ref([]);
const shippingMethod = ref([]);
const productUnit = ref([]);
const sellPerson = ref([]);
const buyPerson = ref([]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
  },
});
const loading = ref(false);
const selectConfig = computed(() => {
  return [
    {
      label: "销售方",
      prop: "sellCorporationId",
      data: corporationList.value,
    },
    {
      label: "采购方",
      prop: "buyCorporationId",
      data: corporationList.value,
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "合同编码",
        slot: "code",
        width: 220,
      },
    },
    {
      attrs: {
        label: "合同金额",
        slot: "amount",
        width: 140,
      },
    },
    {
      attrs: {
        label: "销售方",
        slot: "sellCorporationName",
        "min-width": 200,
      },
    },
    {
      attrs: {
        label: "采购方",
        slot: "buyCorporationName",
        "min-width": 200,
      },
    },
    {
      attrs: {
        label: "最近操作人",
        prop: "opUserName",
        width: 180,
      },
    },
    {
      attrs: {
        label: "最近操作时间",
        prop: "updateTime",
        width: 180,
      },
    },
    {
      attrs: {
        label: "操作",
        width: "120",
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "编辑",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              clickUpdate(row);
            },
          },
          {
            attrs: {
              label: "打印",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              clickPrint(row);
            },
          },
        ];
      },
    },
  ];
});
const getDict = () => {
  proxy.getDictOne(["trade_mode", "shipping_method", "unit"]).then((res) => {
    if (res.trade_mode && res.trade_mode.length > 0) {
      tradeMethods.value = res.trade_mode.map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
    }
    if (res.shipping_method && res.shipping_method.length > 0) {
      shippingMethod.value = res.shipping_method.map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
    }
    if (res.unit && res.unit.length > 0) {
      productUnit.value = res.unit.map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
    }
  });
  proxy.post("/corporation/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    corporationList.value = res.rows.map((item) => {
      return {
        ...item,
        label: item.name,
        value: item.id,
      };
    });
  });
};
const getPerson = () => {
  proxy.post("/intermediateContract/contactList", {}).then((res) => {
    sellPerson.value = res.map((item) => {
      return {
        ...item,
        value: item.sellContactName,
      };
    });
    buyPerson.value = res.map((item) => {
      return {
        ...item,
        value: item.buyContactName,
      };
    });
  });
};
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/intermediateContract/page", sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getDict();
getList();
const openPrint = ref(false);
const printDetails = ref({});
const clickPrint = (row) => {
  printDetails.value = {};
  openPrint.value = true;
  proxy.post("/intermediateContract/getPrintInfo", { documentsId: row.documentsId }).then((res) => {
    printDetails.value = res;
  });
};
const clickDownload = () => {
  proxy.getPdf("外销合同PDF文件");
};
const statistics = (label, index) => {
  let num = 0;
  if (printDetails.value.productInfoList && printDetails.value.productInfoList.length > 0) {
    printDetails.value.productInfoList.map((item) => {
      if (item[label]) {
        num = parseFloat(Number(num) + Number(item[label])).toFixed(index);
      }
    });
  }
  return num;
};
const statisticsTwo = (label, index) => {
  let num = 0;
  if (printDetails.value.contractProjectList && printDetails.value.contractProjectList.length > 0) {
    printDetails.value.contractProjectList.map((item) => {
      if (item[label]) {
        num = parseFloat(Number(num) + Number(item[label])).toFixed(index);
      }
    });
  }
  return num;
};
const pushProcessApproval = (row) => {
  proxy.$router.push({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: "contract_flow",
      id: row.flowId,
      processType: 20,
      random: proxy.random(),
      flowName: "销售合同详情",
    },
  });
  return;
};
const printObj = ref({
  id: "printMe",
  popTitle: "",
  extraCss: "https://cdn.bootcdn.net/ajax/libs/animate.css/4.1.1/animate.compat.css, https://cdn.bootcdn.net/ajax/libs/hover.css/2.3.1/css/hover-min.css",
  extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',
});
const openUpdate = ref(false);
const update = ref(null);
const formData = reactive({
  data: {},
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formConfig = computed(() => {
  return [
    {
      type: "select",
      label: "销售方",
      prop: "sellCorporationId",
      data: corporationList.value,
    },
    {
      type: "slot",
      slotName: "sellContactName",
      prop: "sellContactName",
      label: "销售联系信息",
      itemWidth: 40,
    },
    {
      type: "input",
      prop: "sellContactNumber",
      label: " ",
      itemWidth: 60,
      itemType: "text",
    },
    {
      type: "select",
      label: "采购方",
      prop: "buyCorporationId",
      data: corporationList.value,
    },
    {
      type: "slot",
      slotName: "buyContactName",
      prop: "buyContactName",
      label: "采购联系信息",
      itemWidth: 40,
    },
    {
      type: "input",
      prop: "buyContactNumber",
      label: " ",
      itemWidth: 60,
      itemType: "text",
    },
  ];
});
const rules = ref({
  sellCorporationId: [{ required: true, message: "请选择销售方", trigger: "change" }],
  sellContactName: [{ required: true, message: "请输入销售联系人", trigger: "blur" }],
  sellContactNumber: [{ required: true, message: "请输入销售联系电话", trigger: "blur" }],
  buyCorporationId: [{ required: true, message: "请选择采购方", trigger: "change" }],
  buyContactName: [{ required: true, message: "请输入采购联系人", trigger: "blur" }],
  buyContactNumber: [{ required: true, message: "请输入采购联系电话", trigger: "blur" }],
});
const clickUpdate = (row) => {
  getPerson();
  formData.data = {
    documentsId: row.documentsId,
    sellCorporationId: "",
    sellContactName: "",
    sellContactNumber: "",
    buyCorporationId: "",
    buyContactName: "",
    buyContactNumber: "",
  };
  openUpdate.value = true;
};
const clickSubmit = () => {
  update.value.handleSubmit(() => {
    proxy.post("/intermediateContract/edit", formData.data).then((res) => {
      printDetails.value = res;
      ElMessage({
        message: "编辑成功",
        type: "success",
      });
      openUpdate.value = false;
      getList();
    });
  });
};
const createFilter = (queryString) => {
  return (restaurant) => {
    return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
  };
};
const querySearchSellPerson = (queryString, callback) => {
  const resultsSell = queryString ? sellPerson.value.filter(createFilter(queryString)) : sellPerson.value;
  callback(resultsSell);
};
const handleSellPerson = (item) => {
  formData.data.sellContactNumber = item.sellContactNumber;
};
const querySearchBuyPerson = (queryString, callback) => {
  const resultsBuy = queryString ? buyPerson.value.filter(createFilter(queryString)) : buyPerson.value;
  callback(resultsBuy);
};
const handleBuyPerson = (item) => {
  formData.data.buyContactNumber = item.buyContactNumber;
};
</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
.baseRow {
  min-height: 24px;
  border-top: 1px solid black;
  border-left: 1px solid black;
}
.contentRow {
  border-right: 1px solid black;
  line-height: 24px;
  padding-left: 4px;
}
</style>
