<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 #code="{ item }">
          <div style="width: 100%">
            <a style="color: #409eff; cursor: pointer; word-break: break-all" @click="openDetails(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 #amountCNY="{ item }">
          <div>
            <span>{{ moneyFormat(item.amountCNY, 2) }}</span>
          </div>
        </template>
        <template #sumClaimMoney="{ item }">
          <div>
            <el-popover :width="400" trigger="hover" @show="recordShow(item)">
              <template #reference>
                <a style="color: #409eff; cursor: pointer; word-break: break-all">{{ moneyFormat(item.sumClaimMoney, 2) }}</a>
              </template>
              <template #default>
                <div style="width: 100%; max-height: 60vh; overflow-y: auto; overflow-x: hidden" v-if="item.claimRecord && item.claimRecord.length > 0">
                  <div v-for="(record, index) in item.claimRecord" :key="index" style="margin-bottom: 20px">
                    <div style="display: flex; justify-content: space-between">
                      <span style="color: #909399">{{ record.createTime }}</span>
                      <span style="color: #909399">{{ dictValueLabel(record.createUser, userList) }}</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; padding: 8px 0">
                      <span>认领金额: {{ record.currency }} {{ record.money }}</span>
                      <span>汇率: {{ item.rate }}</span>
                    </div>
                  </div>
                </div>
              </template>
            </el-popover>
          </div>
        </template>
        <template #scale="{ item }">
          <div>
            {{ computeScale(item) }}
          </div>
        </template>
        <template #refundStatusNew="{ item }">
          <div>
            <span v-if="item.refundStatus && item.refundStatus !== 0">
              {{ dictValueLabel(item.refundStatus, refundStatusNew) }}
            </span>
            <span v-else>{{ dictValueLabel(item.refundStatusNew, refundStatusNew) }}</span>
          </div>
        </template>
        <template #status="{ item }">
          <div>
            <span :style="getStyle(item.status)">{{ dictValueLabel(item.status, status) }}</span>
          </div>
        </template>
        <template #buyCorporationId="{ item }">
          <div style="cursor: pointer; color: #409eff; word-break: break-all" @click="handleClickName(item)">
            {{ item.buyCorporationName }}
          </div>
        </template>
      </byTable>
    </div>

    <el-dialog title="打印" v-if="openPrint" v-model="openPrint" width="860">
      <ContractPDF :rowData="rowData"></ContractPDF>
      <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="openDetailsDialog" v-model="openDetailsDialog" width="1000">
      <ContractDetails :contractId="currentContractId"></ContractDetails>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref } from "vue";
import byTable from "@/components/byTable/index";
import useUserStore from "@/store/modules/user";
import { ElMessage, ElMessageBox } from "element-plus";
import ContractDetails from "@/components/contractCom/contractDetails.vue";
import ContractPDF from "@/components/PDF/contractPDF.vue";
const route = useRoute();
const { proxy } = getCurrentInstance();
const contractType = ref([]);
const accountCurrency = ref([]);
const tradeMethods = ref([]);
const corporationList = ref([]);
const customerList = ref([]);
const shippingMethod = ref([]);
const productUnit = ref([]);
const userList = ref([]);
const openDetailsDialog = ref(false);
const status = ref([
  {
    label: "草稿",
    value: 0,
  },
  {
    label: "审批中",
    value: 10,
  },
  {
    label: "驳回",
    value: 20,
  },
  {
    label: "审批通过",
    value: 30,
  },
  {
    label: "终止",
    value: 99,
  },
]);
const refundStatusNew = ref([
  {
    label: "未到款",
    value: 0,
  },
  {
    label: "部分到款",
    value: 10,
  },
  {
    label: "已到款",
    value: 20,
  },
]);
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: "refundStatusNew",
      data: refundStatusNew.value,
    },
    {
      label: "合同类型",
      prop: "contractType",
      data: contractType.value,
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "归属公司",
        prop: "sellCorporationId",
        "min-width": 160,
      },
      render(type) {
        return proxy.dictValueLabel(type, corporationList.value);
      },
    },
    {
      attrs: {
        label: "合同类型",
        prop: "contractType",
        width: 100,
      },
      render(type) {
        return proxy.dictValueLabel(type, contractType.value);
      },
    },
    {
      attrs: {
        label: "合同编码",
        slot: "code",
        width: 160,
      },
    },
    {
      attrs: {
        label: "客户",
        slot: "buyCorporationId",
        "min-width": 180,
      },
    },
    {
      attrs: {
        label: "合同金额",
        slot: "amount",
        width: 140,
        align: "right",
      },
    },
    {
      attrs: {
        label: "合同汇率",
        prop: "rate",
        width: 100,
      },
    },
    {
      attrs: {
        label: "合同金额(CNY)",
        slot: "amountCNY",
        width: 120,
        align: "right",
      },
    },
    {
      attrs: {
        label: "已到账金额(CNY)",
        slot: "sumClaimMoney",
        width: 140,
        align: "right",
      },
    },
    {
      attrs: {
        label: "到账比例",
        slot: "scale",
        width: 100,
      },
    },
    {
      attrs: {
        label: "业务员",
        prop: "createUser",
        width: 140,
      },
      render(type) {
        return proxy.dictValueLabel(type, userList.value);
      },
    },
    {
      attrs: {
        label: "创建时间",
        prop: "createTime",
        width: 160,
      },
    },
    {
      attrs: {
        label: "审批状态",
        prop: "status",
        width: 120,
        slot: "status",
      },
      // render(type) {
      //   return proxy.dictValueLabel(type, status.value);
      // },
    },
    {
      attrs: {
        label: "到款状态",
        slot: "refundStatusNew",
        width: 120,
      },
    },
    {
      attrs: {
        label: "操作",
        width: "180",
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          !row.refundStatus && row.refundStatusNew == 10
            ? {
                attrs: {
                  label: "到款完成",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  clickAccomplish(row);
                },
              }
            : {},
          row.issue && row.issue === "0" && row.status == 30
            ? {
                attrs: {
                  label: "下发交接单",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  ElMessageBox.confirm("是否确认下发交接单?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                  }).then(() => {
                    proxy.post("/contract/edit", { id: row.id, issue: 1 }).then(() => {
                      ElMessage({ message: "下发成功", type: "success" });
                      getList();
                    });
                  });
                },
              }
            : {},
          row.status == 30
            ? {
                attrs: {
                  label: "变更",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  clickAlteration(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(["contract_type", "account_currency", "trade_mode", "shipping_method", "unit"]).then((res) => {
    if (res.contract_type && res.contract_type.length > 0) {
      contractType.value = res.contract_type.map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
    }
    if (res.account_currency && res.account_currency.length > 0) {
      accountCurrency.value = res.account_currency.map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
    }
    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,
      };
    });
  });
  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
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      dictCode: "shipping_method",
      tenantId: useUserStore().user.tenantId,
    })
    .then((res) => {
      if (res.rows && res.rows.length > 0) {
        shippingMethod.value = res.rows.map((item) => {
          return {
            label: item.dictValue,
            value: item.dictKey,
          };
        });
      }
    });
  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) => {
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getDict();
if (route.query.code) {
  sourceList.value.pagination.keyword = route.query.code;
}
getList();
const newContract = () => {
  proxy.$router.replace({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: "contract_flow",
      flowName: "销售合同审批流程",
      random: proxy.random(),
    },
  });
};
const openPrint = ref(false);
const printDetails = ref({});
const rowData = ref({});
const clickPrint = (row) => {
  // printDetails.value = {};
  // openPrint.value = true;
  // proxy.post("/contract/getContractPdfInfo", { id: row.id }).then((res) => {
  //   printDetails.value = res;
  // });

  rowData.value = {
    id: row.id,
  };
  openPrint.value = true;
};
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 computeScale = (item) => {
  let text = 0;
  if (item.sumClaimMoney && Number(item.sumClaimMoney) > 0 && item.amountCNY && Number(item.amountCNY) > 0) {
    text = parseFloat((Number(item.sumClaimMoney) / Number(item.amountCNY)) * 100).toFixed(2);
  }
  return text + "%";
};
const clickAccomplish = (row) => {
  proxy.post("/contract/toTheAccount", { id: row.id }).then(() => {
    getList();
  });
};
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 currentContractId = ref("");
const openDetails = (row) => {
  currentContractId.value = row.id;
  openDetailsDialog.value = true;
};
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 clickAlteration = (row) => {
  proxy.$router.push({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: "contract_update_flow",
      flowName: "销售合同变更流程",
      contractId: row.id,
      random: proxy.random(),
    },
  });
};

const getStyle = (status) => {
  if (status == 10) {
    return {
      color: "#FF9315",
    };
  } else if (status == 30) {
    return {
      color: "#39C55A",
    };
  } else if (status == 20 || status == 99) {
    return {
      color: "#FF655B",
    };
  } else {
    return {};
  }
};
const handleClickName = (row) => {
  proxy.$router.push({
    path: "/ERP/customer/portrait",
    query: {
      id: row.buyCorporationId,
    },
  });
};
const recordShow = (item) => {
  if (!(item.claimRecord && item.claimRecord.length > 0)) {
    proxy.post("/claimContract/getListByContractIds", [item.id]).then((res) => {
      if (res && res.length > 0) {
        item.claimRecord = res;
      }
    });
  }
};
</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>
