<template>
  <div class="pageIndexClass">
    <byTable :source="sourceList.data" :pagination="sourceList.pagination" :config="config" :loading="loading" :selectConfig="selectConfig"
             :row-class-name="getRowClass" highlight-current-row @get-list="getList">
      <template #code="{ item }">
        <div v-if="Number(item.sumPayMoney) > Number(item.amount)" style="cursor: pointer; color: #f54a45" @click="handleClickCode(item)">
          {{ item.code }}
        </div>
        <div v-else style="cursor: pointer; color: #409eff" @click="handleClickCode(item)">
          {{ item.code }}
        </div>
      </template>
      <template #amount="{ item }">
        <div>
          <span style="padding-right: 4px">{{ item.currency }}</span>
          <span>{{ moneyFormat(item.amount, 2) }}</span>
        </div>
      </template>
      <template #sumPayMoney="{ item }">
        <div>
          <span style="padding-right: 4px">{{ item.currency }}</span>
          <span>{{ moneyFormat(item.sumPayMoney, 2) }}</span>
        </div>
      </template>

      <template #payStatus="{ item }">
        <div style="width:100%">
          <span :class="{'tag-active':item.payStatus==20,'tag-active-1':item.payStatus==10}">{{dictValueLabel(item.payStatus, payStatus)}}</span>
        </div>
      </template>

    </byTable>
    <el-dialog title="打印" v-if="openPdf" v-model="openPdf" width="920px">
      <PurchasePDF :rowData="rowData"></PurchasePDF>
      <!-- <PurchasePDFOne :rowData="rowData"></PurchasePDFOne> -->
      <!-- <PurchasePDFOneNew :rowData="rowData" ref="PdfDom"></PurchasePDFOneNew> -->
      <!-- <template #footer ref="printBtn">
        <el-button @click="openPdf = false" size="default">关闭</el-button>
        <el-button type="primary" v-print="printObj" size="default">打印</el-button>
        <el-button type="primary" @click="clickDownload()" size="default">下载PDF</el-button>
        <el-button type="primary" @click="exportExcel()" size="default">导出Excel</el-button>
      </template> -->
    </el-dialog>

    <el-dialog title="到货登记" v-model="arrivalDialog" width="70%" destroy-on-close>
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="formDom" v-loading="submitLoading">
        <template #details>
          <div style="width:100%;padding:0 15px">
            <el-table :data="formData.data.purchaseProductList">
              <el-table-column label="商品图片" width="80">
                <template #default="{ row }">
                  <div v-if="row.fileUrl">
                    <img :src="row.fileUrl" class="pic" @click="openImg(row.fileUrl)" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="productCode" label="商品编码" width="160" />
              <el-table-column prop="productName" label="商品名称" min-width="130" />
              <el-table-column label="尺寸 (cm)" width="140">
                <template #default="{ row, $index }">
                  <div style="width: 100%">
                    {{row.productLength}} * {{row.productWidth}} * {{row.productHeight}}
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="采购数量" prop="quantity" width="100" />
              <el-table-column label="已到货数量" prop="quantity" width="100" />
              <el-table-column prop="contractMoney" label="到货数量" width="130">
                <template #default="{ row, $index }">
                  <el-form-item :prop="'purchaseProductList.' + $index + '.contractMoney'" :rules="rules.contractMoney" :inline-message="true"
                                class="margin-b-0">
                    <el-input-number onmousewheel="return false;" v-model="row.contractMoney" placeholder="请输入" style="width: 100%" :precision="0"
                                     :controls="false" :min="0" />
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="arrivalDialog = false" size="defualt" v-debounce>取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="defualt" v-debounce>
          确 定
        </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 { ElMessage, ElMessageBox } from "element-plus";
import PurchasePDF from "@/components/PDF/purchasePDF.vue";
// import PurchasePDFOne from "@/components/PDF/purchasePDFOne.vue";
// import PurchasePDFOneNew from "@/components/PDF/purchasePDFOneNew.vue";

const route = useRoute();
const { proxy } = getCurrentInstance();
const supplierList = ref([]);
const status = ref([
  {
    label: "草稿",
    value: 0,
  },
  {
    label: "审批中",
    value: 10,
  },
  {
    label: "驳回",
    value: 20,
  },
  {
    label: "已采购",
    value: 30,
  },
  {
    label: "变更中",
    value: 60,
  },
  {
    label: "已变更",
    value: 70,
  },
  {
    label: "作废",
    value: 88,
  },
  {
    label: "终止",
    value: 99,
  },
]);
const payStatus = ref([
  {
    label: "未付款",
    value: 0,
  },
  {
    label: "部分付款",
    value: 10,
  },
  {
    label: "已付款",
    value: 20,
  },
]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    status: "",
    payStatus: "",
  },
});
const loading = ref(false);
const companyData = ref([]);
const selectConfig = computed(() => {
  return [
    {
      label: "归属公司",
      prop: "companyId",
      data: companyData.value,
    },
    {
      label: "采购状态",
      prop: "status",
      data: status.value,
    },
    {
      label: "付款状态",
      prop: "payStatus",
      data: payStatus.value,
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "归属公司",
        prop: "companyName",
        width: 130,
      },
    },
    {
      attrs: {
        label: "采购单号",
        slot: "code",
        width: 180,
      },
    },
    {
      attrs: {
        label: "供应商",
        prop: "sellCorporationId",
        "min-width": 220,
      },
      render(type) {
        return proxy.dictValueLabel(type, supplierList.value);
      },
    },
    {
      attrs: {
        label: "采购金额",
        slot: "amount",
        width: 140,
      },
    },
    {
      attrs: {
        label: "已付款金额",
        slot: "sumPayMoney",
        width: 140,
      },
    },
    {
      attrs: {
        label: "采购人",
        prop: "userName",
        width: 140,
      },
    },
    {
      attrs: {
        label: "采购时间",
        prop: "createTime",
        width: 160,
      },
    },
    {
      attrs: {
        label: "采购状态",
        prop: "status",
        width: 140,
      },
      render(type) {
        return proxy.dictValueLabel(type, status.value);
      },
    },
    {
      attrs: {
        label: "付款状态",
        prop: "payStatus",
        slot: "payStatus",
        width: 140,
      },
      // render(type) {
      //   return proxy.dictValueLabel(type, payStatus.value);
      // },
    },
    {
      attrs: {
        label: "操作",
        width: 200,
        align: "right",
        fixed: "right",
      },
      renderHTML(row) {
        return proxy.isCurrentCompanyData(row.companyId)
          ? [
              row.status == 30
                ? {
                    attrs: {
                      label: "变更",
                      type: "primary",
                      text: true,
                    },
                    el: "button",
                    click() {
                      handleChange(row);
                    },
                  }
                : {},
              row.status == 30
                ? {
                    attrs: {
                      label: "到货登记",
                      type: "primary",
                      text: true,
                    },
                    el: "button",
                    click() {
                      handleArrival(row);
                    },
                  }
                : {},
              {
                attrs: {
                  label: "打印",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  handlePrintPdf(row);
                },
              },
              // && Number(row.amount) > Number(row.sumPayMoney)
              row.status == 10 ||
              (row.status == 30 && Number(row.sumPayMoney) == 0)
                ? {
                    attrs: {
                      label: "作废",
                      type: "danger",
                      text: true,
                    },
                    el: "button",
                    click() {
                      ElMessageBox.confirm(
                        "此操作将作废该数据, 是否继续?",
                        "提示",
                        {
                          confirmButtonText: "确定",
                          cancelButtonText: "取消",
                          type: "warning",
                        }
                      ).then(() => {
                        proxy
                          .post("/ehsdPurchase/cancellation", {
                            id: row.id,
                            status: 88,
                          })
                          .then(() => {
                            ElMessage({
                              message: "作废成功",
                              type: "success",
                            });
                            getList();
                          });
                      });
                    },
                  }
                : {},
              row.status == 30 && Number(row.amount) > Number(row.sumPayMoney)
                ? {
                    attrs: {
                      label: "终止",
                      type: "primary",
                      text: true,
                    },
                    el: "button",
                    click() {
                      ElMessageBox.confirm(
                        "此操作将终止该数据, 是否继续?",
                        "提示",
                        {
                          confirmButtonText: "确定",
                          cancelButtonText: "取消",
                          type: "warning",
                        }
                      ).then(() => {
                        proxy
                          .post("/ehsdPurchase/edit", {
                            id: row.id,
                            status: 99,
                          })
                          .then(() => {
                            ElMessage({
                              message: "终止",
                              type: "success",
                            });
                            getList();
                          });
                      });
                    },
                  }
                : {},
            ]
          : [];
      },
    },
  ];
});
const getDict = () => {
  proxy
    .post("/supplierInfo/page", { pageNum: 1, pageSize: 999 })
    .then((res) => {
      supplierList.value = res.rows.map((item) => {
        return {
          ...item,
          label: item.name,
          value: item.id,
        };
      });
    });

  proxy
    .get("/tenantDept/list", {
      pageNum: 1,
      pageSize: 9999,
      keyword: "",
      tenantId: proxy.useUserStore().user.tenantId,
      type: 0,
    })
    .then((res) => {
      companyData.value = res.data.map((x) => ({
        ...x,
        label: x.deptName,
        value: x.deptId,
      }));
      // treeData.value = proxy.handleTree(res.data, "deptId");
    });
};
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/ehsdPurchase/page", sourceList.value.pagination).then((res) => {
    console.log(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 openPdf = ref(false);
const pdfData = ref({});
const rowData = ref({});
const handlePrintPdf = (row) => {
  rowData.value = {
    id: row.id,
    code: row.code,
  };
  rowData.value = row;
  openPdf.value = true;
};
const clickDownload = () => {
  proxy.getPdf("购销合同" + rowData.value.code);
};
const pdfDom = ref(null);
const printObj = ref({
  id: "pdfDom",
  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 handleClickCode = (row) => {
  // let submitType = row.dataResource > 0 ? "10" : "20";
  proxy.$router.push({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: "purchase_flow",
      id: row.flowId,
      processType: 20,
      businessId: row.id,
      // submitType,
    },
  });
};

const getRowClass = ({ row }) => {
  if (Number(row.sumPayMoney) > Number(row.amount)) {
    return "redClass";
  }
  return "";
};

const handleChange = (row) => {
  let submitType = row.dataResource > 0 ? "10" : "20";
  let type = "";
  if (row.dataResource == 1) {
    type = 1;
  } else if (row.dataResource == 2) {
    type = 2;
  }
  proxy.$router.push({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: "purchase_update_flow",
      flowName: "采购合同变更",
      random: proxy.random(),
      businessId: row.id,
      submitType,
      type,
    },
  });
};

const formData = reactive({
  data: {},
});
const formOption = reactive({
  inline: true,
  labelWidth: 110,
  itemWidth: 100,
  rules: [],
});
const formConfig = computed(() => {
  return [
    {
      type: "title1",
      title: "基本信息",
    },
    {
      type: "input",
      prop: "code",
      label: "采购单号",
      itemWidth: 50,
      disabled: true,
    },
    {
      type: "input",
      prop: "sellCorporationName",
      label: "供应商",
      itemWidth: 50,
      disabled: true,
    },
    {
      type: "date",
      prop: "aa",
      label: "到货日期",
      itemType: "date",
      itemWidth: 50,
    },
    {
      type: "title1",
      title: "到货明细",
    },
    {
      type: "slot",
      slotName: "details",
      label: "",
    },
  ];
});
const rules = ref({
  productSn: [{ required: true, message: "请输入商品Sn", trigger: "blur" }],
  type: [{ required: true, message: "请选择售后类型", trigger: "change" }],
  remark: [{ required: true, message: "请输入售后说明", trigger: "blur" }],
  contactName: [
    { required: true, message: "请输入客户联系人", trigger: "blur" },
  ],
  contactInfo: [
    { required: true, message: "请输入客户联系方式", trigger: "blur" },
  ],
  afterSalesPersonId: [
    { required: true, message: "请选择售后人员", trigger: "change" },
  ],
  quantity: [{ required: true, message: "请输入数量", trigger: "blur" }],
});

const formDom = ref(null);
const arrivalDialog = ref(false);
const handleArrival = (row) => {
  proxy.post("/ehsdPurchase/detail", { id: row.id }).then((res) => {
    formData.data = res;
    if (
      formData.data.purchaseProductList &&
      formData.data.purchaseProductList.length > 0
    ) {
      let productIds = formData.data.purchaseProductList.map(
        (x) => x.productId
      );
      proxy.getFileData({
        businessIdList: productIds,
        data: formData.data.purchaseProductList,
        att: "productId",
        businessType: "0",
        fileAtt: "fileList",
        filePathAtt: "fileUrl",
      });
    }
  });
  arrivalDialog.value = true;
};
const submitForm = () => {
  formDom.value.handleSubmit(() => {
    submitLoading.value = true;
    proxy.post("/afterSalesRecord/add", formData.data).then(
      (res) => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        dialogVisible.value = false;
        submitLoading.value = false;
        getList();
      },
      (err) => {
        submitLoading.value = false;
      }
    );
  });
};

const PdfDom = ref(null);
const exportExcel = () => {
  PdfDom.value.exportExcel();
};
</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>
<style>
.redClass {
  color: #f54a45 !important;
}
</style>
