<template>
  <div class="tenant">
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        :selectConfig="selectConfig"
        highlight-current-row
        :action-list="[
          {
            text: '新建销售合同',
            action: () => newContract(),
          },
        ]"
        @get-list="getList">
        <template #amount="{ item }">
          <div>
            <span style="padding-right: 4px">{{ item.currency }}</span>
            <span>{{ moneyFormat(item.amount, 2) }}</span>
          </div>
        </template>
        <template #buyCorporationName="{ item }">
          <div style="width: 100%">
            <a style="color: #409eff; cursor: pointer" @click="clickCorporationName(item.buyCorporationName)">{{ item.buyCorporationName }}</a>
          </div>
        </template>
        <template #tags="{ item }">
          <div style="width: 100%">
            <el-tag style="margin-right: 8px" type="success" v-for="(tag, index) in item.tags" closable :key="index" @close="tagClose(tag, item)">
              {{ dictValueLabel(tag, customerTag) }}
            </el-tag>
            <template v-if="item.tags.length !== customerTag.length">
              <el-select
                v-if="item.addTagShow"
                v-model="addTag"
                style="width: 100%"
                @change="
                  (val) => {
                    return changeTag(val, item);
                  }
                ">
                <el-option v-for="tag in customerTag" :key="tag.value" :label="tag.label" :value="tag.value" :disabled="judgeTagSelect(item.tags, tag.value)" />
              </el-select>
              <el-tag style="cursor: pointer" type="success" @click="showSelect(item)" v-else> + </el-tag>
            </template>
          </div>
        </template>
        <template #advanceRatio="{ item }">
          <div>
            <span>{{ item.advanceRatio }}%</span>
          </div>
        </template>
      </byTable>
    </div>

    <el-dialog title="打印" v-if="openPrint" v-model="openPrint" width="860">
      <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>{{ printDetails.sellContactName }},{{ printDetails.sellContactNumber }}</div>
          </div>
          <div style="width: 50%">
            <div style="color: #409eff">BUYER:</div>
            <div>{{ printDetails.buyCorporationName }}</div>
            <div style="padding: 16px 0">
              {{ printDetails.buyCountryName }},{{ printDetails.buyProvinceName }},{{ printDetails.buyCityName }},{{ printDetails.buyDetailedAddress }}
            </div>
            <div>{{ printDetails.buyContactName }},{{ 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>
                {{ dictValueLabel(printDetails.currency, accountCurrency) }}
              </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">
              {{ item.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 v-if="printDetails.quotationPayList && printDetails.quotationPayList.length > 0">
          <div class="baseRow" style="display: flex" v-for="(item, index) in printDetails.quotationPayList" :key="index">
            <div class="contentRow" style="width: calc(100% - 100px); text-align: right; color: #409eff">{{ item.payName }}:</div>
            <div class="contentRow" style="width: 100px; text-align: center">{{ item.amount }}</div>
          </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">0</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">
            {{ statistics("amount", 2) }}
          </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>
      <template #footer>
        <el-button @click="openPrint = false" size="large">取消</el-button>
        <el-button type="primary" @click="clickDownload()" size="large">下载PDF</el-button>
      </template>
    </el-dialog>

    <el-dialog title="交接单" v-if="openHandoverSlip" v-model="openHandoverSlip" width="600">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="handoverSlipForm">
        <template #file>
          <div style="width: 100%">
            <el-upload
              v-model:fileList="handoverSlipForm.fileList"
              action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
              :data="uploadData"
              multiple
              :before-upload="uploadFile"
              :on-success="handleSuccess"
              :on-preview="onPreviewFile">
              <el-button type="primary" plain>选择</el-button>
            </el-upload>
          </div>
        </template>
        <template #indication>
          <div style="width: 100%">
            <el-upload
              v-model:fileList="handoverSlipForm.packageFileList"
              action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
              :data="indicationUploadData"
              multiple
              :before-upload="indicationUploadFile"
              :on-success="handleSuccess"
              :on-preview="onPreviewFile">
              <el-button type="primary" plain>选择</el-button>
            </el-upload>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="openHandoverSlip = false" size="large">关 闭</el-button>
        <el-button type="primary" @click="submitHandoverSlip()" size="large">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

const { proxy } = getCurrentInstance();
const accountCurrency = ref([]);
const tradeMethods = ref([]);
const corporationList = ref([]);
const customerList = ref([]);
const userList = ref([]);
const shippingMethod = ref([]);
const customerTag = ref([]);
const status = ref([
  {
    label: "草稿",
    value: 0,
  },
  {
    label: "审批中",
    value: 10,
  },
  {
    label: "驳回",
    value: 20,
  },
  {
    label: "审批通过",
    value: 30,
  },
  {
    label: "终止",
    value: 99,
  },
]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    status: "",
    sellCorporationId: "",
  },
});
const loading = ref(false);
const selectConfig = computed(() => {
  return [
    {
      label: "审批状态",
      prop: "status",
      data: status.value,
    },
    {
      label: "归属公司",
      prop: "sellCorporationId",
      data: corporationList.value,
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "合同编号",
        prop: "code",
        width: 180,
      },
    },
    {
      attrs: {
        label: "归属公司",
        prop: "sellCorporationId",
        "min-width": 220,
      },
      render(type) {
        return proxy.dictValueLabel(type, corporationList.value);
      },
    },
    {
      attrs: {
        label: "业务员",
        prop: "createUser",
        width: 140,
      },
      render(type) {
        return proxy.dictValueLabel(type, userList.value);
      },
    },
    {
      attrs: {
        label: "下单时间",
        prop: "createTime",
        width: 160,
      },
    },
    {
      attrs: {
        label: "客户名称",
        slot: "buyCorporationName",
        "min-width": 220,
      },
    },
    {
      attrs: {
        label: "客户标签",
        slot: "tags",
        width: 180,
      },
    },
    {
      attrs: {
        label: "合同金额",
        slot: "amount",
        width: 140,
      },
    },
    {
      attrs: {
        label: "预付比例",
        slot: "advanceRatio",
        width: 140,
      },
    },
    {
      attrs: {
        label: "审批状态",
        prop: "status",
        width: 140,
      },
      render(type) {
        return proxy.dictValueLabel(type, status.value);
      },
    },
    {
      attrs: {
        label: "操作",
        width: 160,
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "交接单",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              clickHandoverSlip(row);
            },
          },
          {
            attrs: {
              label: "打印",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              clickPrint(row);
            },
          },
          {
            attrs: {
              label: "作废",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              ElMessageBox.confirm("此操作将永久删除该数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }).then(() => {
                proxy
                  .post("/contract/edit", {
                    id: row.id,
                    status: 88,
                  })
                  .then(() => {
                    ElMessage({
                      message: "作废成功",
                      type: "success",
                    });
                    getList();
                  });
              });
            },
          },
        ];
      },
    },
  ];
});
const getDict = () => {
  proxy.getDictOne(["customer_tag", "trade_methods", "account_currency", "shipping_method"]).then((res) => {
    customerTag.value = res["customer_tag"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
    tradeMethods.value = res["trade_methods"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
    accountCurrency.value = res["account_currency"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
    shippingMethod.value = res["shipping_method"].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,
      };
    });
  });
  proxy.post("/customer/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    customerList.value = res.rows.map((item) => {
      return {
        ...item,
        label: item.name,
        value: item.id,
      };
    });
  });
  proxy
    .get("/tenantUser/list", {
      pageNum: 1,
      pageSize: 10000,
      tenantId: useUserStore().user.tenantId,
    })
    .then((res) => {
      userList.value = res.rows.map((item) => {
        return {
          label: item.nickName,
          value: item.userId,
        };
      });
    });
};
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/contract/page", sourceList.value.pagination).then((res) => {
    res.rows.forEach((x) => {
      x.addTagShow = false;
      if (x.tag) {
        x.tags = x.tag.split(",");
      } else {
        x.tags = [];
      }
    });
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getDict();
getList();
const newContract = () => {
  proxy.$router.replace({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: "contract_flow",
      flowName: "销售合同审批流程",
      random: proxy.random(),
      tenantType: "EHSD",
    },
  });
};
const openPrint = ref(false);
const printDetails = ref({});
const clickPrint = (row) => {
  printDetails.value = {};
  openPrint.value = true;
  proxy.post("/contract/getContractPdfInfo", { id: row.id }).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 openHandoverSlip = ref(false);
const handoverSlipForm = ref({
  id: "",
  code: "",
  buyCorporationName: "",
  fileList: [],
  packageFileList: [],
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "code",
      label: "合同编号",
      itemType: "text",
      disabled: true,
    },
    {
      type: "input",
      prop: "buyCorporationName",
      label: "客户名称",
      itemType: "text",
      disabled: true,
    },
    {
      type: "slot",
      slotName: "file",
      label: "交接单",
    },
    {
      type: "slot",
      slotName: "indication",
      label: "包装指示",
    },
  ];
});
const uploadData = ref({});
const indicationUploadData = ref({});
const clickHandoverSlip = (item) => {
  handoverSlipForm.value.id = item.id;
  handoverSlipForm.value.code = item.code;
  handoverSlipForm.value.buyCorporationName = item.buyCorporationName;
  if (item.fileInfoVos && item.fileInfoVos.length > 0) {
    handoverSlipForm.value.fileList = item.fileInfoVos.map((item) => {
      return {
        raw: item,
        name: item.fileName,
        url: item.fileUrl,
      };
    });
  } else {
    handoverSlipForm.value.fileList = [];
  }
  if (item.packageFileInfoVOList && item.packageFileInfoVOList.length > 0) {
    handoverSlipForm.value.packageFileList = item.packageFileInfoVOList.map((item) => {
      return {
        raw: item,
        name: item.fileName,
        url: item.fileUrl,
      };
    });
  } else {
    handoverSlipForm.value.packageFileList = [];
  }
  openHandoverSlip.value = true;
};
const uploadFile = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  file.uploadState = true;
  return true;
};
const indicationUploadFile = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  indicationUploadData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  file.uploadState = true;
  return true;
};
const handleSuccess = (any, UploadFile) => {
  UploadFile.raw.uploadState = false;
};
const onPreviewFile = (file) => {
  window.open(file.raw.fileUrl, "_blank");
};
const submitHandoverSlip = () => {
  if (handoverSlipForm.value.fileList && handoverSlipForm.value.fileList.length > 0) {
    for (let i = 0; i < handoverSlipForm.value.fileList.length; i++) {
      if (handoverSlipForm.value.fileList[i].raw.uploadState) {
        return ElMessage("文件上传中,请稍后提交");
      }
    }
  }
  if (handoverSlipForm.value.packageFileList && handoverSlipForm.value.packageFileList.length > 0) {
    for (let i = 0; i < handoverSlipForm.value.packageFileList.length; i++) {
      if (handoverSlipForm.value.packageFileList[i].raw.uploadState) {
        return ElMessage("文件上传中,请稍后提交");
      }
    }
  }
  let data = proxy.deepClone(handoverSlipForm.value);
  if (data.fileList && data.fileList.length > 0) {
    data.fileList = data.fileList.map((item) => {
      return {
        id: item.raw.id,
        fileName: item.raw.fileName,
        fileUrl: item.raw.fileUrl,
      };
    });
  } else {
    data.fileList = [];
  }
  if (data.packageFileList && data.packageFileList.length > 0) {
    data.packageFileList = data.packageFileList.map((item) => {
      return {
        id: item.raw.id,
        fileName: item.raw.fileName,
        fileUrl: item.raw.fileUrl,
      };
    });
  } else {
    data.packageFileList = [];
  }
  proxy.post("/contract/contractHandover", data).then(() => {
    ElMessage({
      message: "操作成功！",
      type: "success",
    });
    openHandoverSlip.value = false;
    getList();
  });
};
const addTag = ref("");
const judgeTagSelect = (data, val) => {
  if (data && data.length > 0) {
    if (data.includes(val)) {
      return true;
    }
  }
  return false;
};
const changeTag = (val, item) => {
  let data = {
    id: item.buyCorporationId,
    tag: proxy.deepClone(item.tags),
  };
  data.tag.push(val);
  data.tag = data.tag.join(",");
  proxy.post("/customer/editTag", data).then(() => {
    ElMessage({
      message: "添加成功",
      type: "success",
    });
    item.addTagShow = false;
    addTag.value = "";
    getList();
  });
};
const tagClose = (val, item) => {
  let data = {
    id: item.buyCorporationId,
    tag: proxy.deepClone(item.tags),
  };
  data.tag = data.tag.filter((row) => row !== val);
  if (data.tag && data.tag.length > 0) {
    data.tag = data.tag.join(",");
  } else {
    data.tag = "";
  }
  proxy.post("/customer/editTag", data).then(() => {
    ElMessage({
      message: "添加成功",
      type: "success",
    });
    item.addTagShow = false;
    addTag.value = "";
    getList();
  });
};
const showSelect = (item) => {
  item.addTagShow = true;
};
const clickCorporationName = (name) => {
  proxy.$router.replace({
    path: "/ERP/customer/privatesea",
    query: {
      name: name,
    },
  });
};
</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>
