<template>
  <div>
    <el-card class="box-card">
      <el-tabs v-model="activeName" type="card" @tab-change="changeActiveName">
        <el-tab-pane label="待采购列表" name="first">
          <byTable
            :source="sourceList.data"
            :pagination="sourceList.pagination"
            :config="config"
            :loading="loading"
            :searchConfig="searchConfig"
            highlight-current-row
            @get-list="getList"
            @clickReset="clickReset">
            <template #code="{ item }">
              <div>
                <a style="color: #409eff; cursor: pointer; word-break: break-all" @click="clickCode(item)">{{ item.code }}</a>
              </div>
            </template>
          </byTable>
        </el-tab-pane>
        <el-tab-pane label="采购合同" name="second">
          <byTable
            :source="sourceListTwo.data"
            :pagination="sourceListTwo.pagination"
            :config="configTwo"
            :loading="loading"
            :searchConfig="searchConfigTwo"
            highlight-current-row
            @get-list="getListTwo"
            @clickReset="clickResetTwo">
            <template #typeExpand="{ item }">
              <div style="padding: 0 20px">
                <el-table :data="item.purchaseBomList" :row-style="{ height: '35px' }" header-row-class-name="tableHeader" border>
                  <el-table-column label="品号" prop="bomSpecCode" width="120" />
                  <el-table-column label="品名" prop="bomSpecName" min-width="240" />
                  <el-table-column label="颜色" prop="bomSpecColour" width="180" />
                  <el-table-column label="尺寸（长宽高，cm）" width="160">
                    <template #default="{ row }">
                      <div>{{ row.bomSpecLength }} * {{ row.bomSpecWidth }} * {{ row.bomSpecHeight }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column label="含税单价" prop="unitPrice" width="140" />
                  <el-table-column label="税率" prop="taxRate" width="120" />
                  <el-table-column label="不含税单价" width="100">
                    <template #default="{ row }">
                      <div>{{ moneyFormat(Number(Math.round(((row.unitPrice * 100) / (100 + row.taxRate)) * 100) / 100)) }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column label="采购数量" prop="purchaseQuantity" width="120" />
                  <el-table-column label="含税小计" align="right" width="140">
                    <template #default="{ row }">
                      <div>{{ moneyFormat(Number(Math.round(row.unitPrice * row.purchaseQuantity * 100) / 100)) }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column label="不含税小计" align="right" width="140">
                    <template #default="{ row }">
                      <div>
                        {{
                          moneyFormat(
                            Number(Math.round((Math.round(((row.unitPrice * 100) / (100 + row.taxRate)) * 100) / 100) * row.purchaseQuantity * 100) / 100)
                          )
                        }}
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </template>
            <template #code="{ item }">
              <div>
                <a style="color: #409eff; cursor: pointer; word-break: break-all" @click="clickPurchaseCode(item)">{{ item.code }}</a>
              </div>
            </template>
            <template #advancePayment="{ item }">
              <div>{{ item.advancePayment }}%</div>
            </template>
            <template #finalPayment="{ item }">
              <div>{{ 100 - item.advancePayment }}%</div>
            </template>
          </byTable>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog title="打印" v-if="openPrint" v-model="openPrint" width="800px" v-loading="loadingPrint">
      <div style="height: calc(100vh - 174px); overflow-y: auto; overflow-x: hidden">
        <div id="printMe">
          <div class="con">
            <div style="font-size: 24px; font-weight: 700; padding: 16px; text-align: center">福清市胜德体育用品有限公司</div>
            <div style="font-size: 24px; padding: 8px 0 4px 0; text-align: center; border-bottom: 2px solid black">采购合同</div>
            <div style="height: 8px"></div>
            <table cellspacing="0" cellpadding="0" border="0" style="width: 100%; line-height: 24px">
              <tr>
                <td style="width: 50%">
                  <span>需方：福清市胜德体育用品有限公司</span>
                </td>
                <td>
                  <span>订单号：{{ pdfDetail.purchaseContract.code }}</span>
                </td>
              </tr>
              <tr>
                <td style="width: 50%">
                  <span>供方：{{ pdfDetail.supplier.name }}</span>
                </td>
                <td>
                  <span>日期：{{ pdfDetail.purchaseContract.createTime }}</span>
                </td>
              </tr>
            </table>
            <div style="height: 8px"></div>
            <table cellspacing="0" cellpadding="0" border="0" class="tableOne">
              <tr>
                <th style="width: 30px">序号</th>
                <th style="width: 100px">品号</th>
                <th style="width: 280px">产品名称</th>
                <th style="width: 45px">数量</th>
                <!-- <th style="width: 45px">单位</th> -->
                <th style="width: 45px">单价</th>
                <th style="width: 60px">金额</th>
                <th style="width: 110px">交货期</th>
              </tr>
              <template v-if="pdfDetail.purchaseContract.purchaseBomList && pdfDetail.purchaseContract.purchaseBomList.length > 0">
                <tr v-for="(item, index) in pdfDetail.purchaseContract.purchaseBomList" :key="index">
                  <td>
                    {{ index + 1 }}
                  </td>
                  <td style="text-align: left; word-break: break-all">
                    <span>{{ item.bomSpecCode }}</span>
                  </td>
                  <td style="text-align: left; word-break: break-all; padding: 0 4px">
                    <span>{{ item.bomSpecName }}</span>
                  </td>
                  <td>
                    <span>{{ item.purchaseQuantity }}</span>
                  </td>
                  <!-- <td>
                    <span>{{ item.bomCompany }}</span>
                  </td> -->
                  <td>
                    <span>{{ item.unitPrice }}</span>
                  </td>
                  <td>
                    <span>{{ moneyFormat(Number(Math.round(item.purchaseQuantity * item.unitPrice)), 2) }}</span>
                  </td>
                  <td style="text-align: left; word-break: break-all">
                    <span>{{ pdfDetail.purchaseContract.deliveryDate }}</span>
                  </td>
                </tr>
              </template>
              <tr>
                <td>合计:</td>
                <td colspan="2"></td>
                <td>{{ computeQuantity() }}</td>
                <!-- <td colspan="2"></td> -->
                <td></td>
                <td>
                  <span>{{ moneyFormat(pdfDetail.purchaseContract.totalAmountIncludingTax, 2) }}</span>
                </td>
                <td style="border-right: 0"></td>
              </tr>
            </table>
            <div style="height: 8px"></div>
            <table cellspacing="0" cellpadding="0" border="0" class="tableTwo">
              <tr>
                <td>
                  <div crossOrigin="anonymous" class="ql-snow" v-html="limitImg(pdfDetail.purchaseContract.contract)"></div>
                </td>
              </tr>
            </table>
            <div style="height: 32px"></div>
            <table cellspacing="0" cellpadding="0" border="0" class="tableThree">
              <tr>
                <td style="width: 50%; position: relative; padding-right: 4px">
                  <div>
                    <span>需方（签章）：福清市胜德体育用品有限公司</span>
                  </div>
                  <div style="position: absolute; top: -50px; left: 20px">
                    <!-- <img
                      v-if="pdfDetail.company.companySeal"
                      style="width: 160px; height: 160px"
                      :src="pathPrefix + pdfDetail.company.companySeal"
                      alt=""
                      srcset="" /> -->
                    <img
                      style="width: 160px; height: 160px"
                      :src="'http://www.printmat.cn:8181/file/upload/2023/02/24/20230224180954A0974981a85a2400425eb03c2c3f588a9711.png'"
                      alt=""
                      srcset="" />
                  </div>
                </td>
                <td style="padding-left: 4px">
                  <span>供方（签章）：{{ pdfDetail.supplier.name }}</span>
                </td>
              </tr>
              <tr>
                <td style="width: 50%; padding-right: 4px">
                  <span>税 号：91350181MA8TYY2T6D</span>
                </td>
                <td style="padding-left: 4px">
                  <span>税 号：{{ pdfDetail.supplier.dutyNumber }}</span>
                </td>
              </tr>
              <tr>
                <td style="width: 50%; padding-right: 4px">
                  <span>开 户：中国工商银行股份有限公司福清高山侨乡支行</span>
                </td>
                <td style="padding-left: 4px">
                  <span>开 户：{{ pdfDetail.supplier.bank }}</span>
                </td>
              </tr>
              <tr>
                <td style="width: 50%; padding-right: 4px">
                  <span>账 号：1402073809100001586</span>
                </td>
                <td style="padding-left: 4px">
                  <span>账 号：{{ pdfDetail.supplier.bankAccountNumber }}</span>
                </td>
              </tr>
              <tr>
                <td style="width: 50%; padding-right: 4px">
                  <span>地 址：福建省福州市福清市三山镇横坑村金园路18号3号楼4层</span>
                </td>
                <td style="padding-left: 4px">
                  <span>地 址：{{ pdfDetail.supplier.province }} {{ pdfDetail.supplier.city }} {{ pdfDetail.supplier.detailedAddress }}</span>
                </td>
              </tr>
              <tr>
                <td style="width: 50%; padding-right: 4px">
                  <span>电 话：0591-22852156</span>
                </td>
                <td style="padding-left: 4px">
                  <span>电 话：{{ pdfDetail.supplier.companyTelephone }}</span>
                </td>
              </tr>
            </table>
          </div>
        </div>
      </div>
      <div style="text-align: center; margin: 10px">
        <el-button @click="openPrint = false" size="large">取消</el-button>
        <el-button type="primary" v-print="printObj" size="large">打印</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import byTable from "/src/components/byTable/index";
import { ElMessage, ElMessageBox } from "element-plus";
import { flowStatus } from "/src/utils/flowStatus";

const { proxy } = getCurrentInstance();
const activeName = ref("first");
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    code: "",
    beginTime: "",
    endTime: "",
    flowStatus: "2",
  },
});
const sourceListTwo = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    code: "",
    flowStatus: "",
    supplierName: "",
  },
});
const loading = ref(false);
const searchConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "code",
      label: "申购单号",
    },
    {
      type: "date",
      propList: ["beginTime", "endTime"],
      label: "申购日期",
    },
  ];
});
const searchConfigTwo = computed(() => {
  return [
    {
      type: "input",
      prop: "code",
      label: "采购单号",
    },
    {
      type: "select",
      prop: "flowStatus",
      data: flowStatus(),
      label: "流程状态",
    },
    {
      type: "input",
      prop: "supplierName",
      label: "供应商",
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "申购单号",
        slot: "code",
        width: 220,
      },
    },
    {
      attrs: {
        label: "申购时间",
        prop: "applyTime",
        align: "center",
        width: 160,
      },
    },
    {
      attrs: {
        label: "申购人",
        prop: "applyName",
        width: 160,
      },
    },
    {
      attrs: {
        label: "申购说明",
        prop: "remark",
      },
    },
    {
      attrs: {
        label: "操作",
        width: 80,
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "采购",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              clickPurchase(row);
            },
          },
        ];
      },
    },
  ];
});
const configTwo = computed(() => {
  return [
    {
      type: "expand",
      attrs: {
        label: " ",
        slot: "typeExpand",
        width: 50,
      },
    },
    {
      attrs: {
        label: "采购单号",
        slot: "code",
        width: 160,
      },
    },
    {
      attrs: {
        label: "申购单号",
        prop: "applyBuyCode",
        width: 160,
      },
    },
    {
      attrs: {
        label: "状态",
        prop: "flowStatus",
        width: 100,
      },
      render(val) {
        return proxy.dictKeyValue(val, flowStatus());
      },
    },
    {
      attrs: {
        label: "币种",
        prop: "currency",
        width: 100,
      },
      render(val) {
        return proxy.dictKeyValue(val, proxy.useUserStore().allDict["currency"]);
      },
    },
    {
      attrs: {
        label: "预付款",
        slot: "advancePayment",
        width: 80,
      },
    },
    {
      attrs: {
        label: "尾款",
        slot: "finalPayment",
        width: 80,
      },
    },
    {
      attrs: {
        label: "含税总金额",
        prop: "totalAmountIncludingTax",
        width: 120,
        align: "right",
      },
    },
    {
      attrs: {
        label: "不含税总金额",
        prop: "totalAmountExcludingTax",
        width: 120,
        align: "right",
      },
    },
    {
      attrs: {
        label: "结算方式",
        prop: "settlementMethod",
        width: 120,
      },
      render(val) {
        return proxy.dictKeyValue(val, proxy.useUserStore().allDict["settlement_method"]);
      },
    },
    {
      attrs: {
        label: "发票类型",
        prop: "invoiceType",
        width: 140,
      },
      render(val) {
        return proxy.dictKeyValue(val, proxy.useUserStore().allDict["invoice_type"]);
      },
    },
    {
      attrs: {
        label: "交期",
        prop: "deliveryDate",
        width: 160,
      },
    },
    {
      attrs: {
        label: "供应商",
        prop: "supplierName",
        "min-width": 160,
      },
    },
    {
      attrs: {
        label: "创建时间",
        prop: "createTime",
        width: 160,
      },
    },
    {
      attrs: {
        label: "操作",
        width: 120,
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          row.flowStatus == 2
            ? {
                attrs: {
                  label: "打印",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  clickPrint(row);
                },
              }
            : {},
          row.flowStatus == 0 || row.flowStatus == 3
            ? {
                attrs: {
                  label: "编辑",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  clickUpdate(row);
                },
              }
            : {},
          row.flowStatus == 0 || row.flowStatus == 3
            ? {
                attrs: {
                  label: "删除",
                  type: "danger",
                  text: true,
                },
                el: "button",
                click() {
                  clickDelete(row);
                },
              }
            : {},
        ];
      },
    },
  ];
});
const getList = (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/applyBuy/page", sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getList();
const clickReset = () => {
  getList("");
};
const getListTwo = (req, status) => {
  if (status) {
    sourceListTwo.value.pagination = {
      pageNum: sourceListTwo.value.pagination.pageNum,
      pageSize: sourceListTwo.value.pagination.pageSize,
    };
  } else {
    sourceListTwo.value.pagination = { ...sourceListTwo.value.pagination, ...req };
  }
  loading.value = true;
  proxy.post("/purchase/page", sourceListTwo.value.pagination).then((res) => {
    sourceListTwo.value.data = res.rows;
    sourceListTwo.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
const clickResetTwo = () => {
  getListTwo("", true);
};
const changeActiveName = (val) => {
  if (val === "first") {
    getList();
  } else {
    getListTwo();
  }
};
const clickCode = (item) => {
  proxy.$router.replace({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: "apply_buy",
      flowName: "申购流程",
      processType: "20",
      id: item.id,
      flowId: item.flowId,
      random: proxy.random(),
    },
  });
};
const clickPurchaseCode = (item) => {
  proxy.$router.replace({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: "purchase",
      flowName: "采购流程",
      processType: "20",
      id: item.id,
      flowId: item.flowId,
      random: proxy.random(),
    },
  });
};
const clickPurchase = (item) => {
  proxy.$router.replace({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: "purchase",
      flowName: "采购流程",
      random: proxy.random(),
      subscribeId: item.id,
    },
  });
};
const clickUpdate = (item) => {
  proxy.$router.replace({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: "purchase",
      flowName: "采购流程",
      processType: "40",
      id: item.id,
      random: proxy.random(),
    },
  });
};
const clickDelete = (row) => {
  ElMessageBox.confirm("你是否确认此操作", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      proxy.post("/purchase/delete", { id: row.id }).then(() => {
        ElMessage({ message: "删除成功", type: "success" });
        getListTwo();
      });
    })
    .catch(() => {});
};
const openPrint = ref(false);
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 pdfDetail = ref({
  purchaseContract: {},
  supplier: {},
});
const loadingPrint = ref(false);
const clickPrint = async (row) => {
  pdfDetail.value = {
    purchaseContract: {},
    supplier: {},
  };
  openPrint.value = true;
  loadingPrint.value = true;
  let supplier = await proxy.post("/supplier/detail", { id: row.supplierId }).then((res) => {
    pdfDetail.value.supplier = res;
  });
  let purchase = await proxy.post("/purchase/detail", { id: row.id }).then((res) => {
    pdfDetail.value.purchaseContract = res;
  });
  loadingPrint.value = false;
};
const limitImg = (text) => {
  if (text) {
    return text.replace(/<img/g, '<img style="max-width: 98%;"');
  } else {
    return text;
  }
};
const computeQuantity = () => {
  let num = 0;
  if (pdfDetail.value.purchaseContract.purchaseBomList && pdfDetail.value.purchaseContract.purchaseBomList.length > 0) {
    for (let i = 0; i < pdfDetail.value.purchaseContract.purchaseBomList.length; i++) {
      if (pdfDetail.value.purchaseContract.purchaseBomList[i].purchaseQuantity) {
        num = Number(Math.round(num + pdfDetail.value.purchaseContract.purchaseBomList[i].purchaseQuantity));
      }
    }
  }
  return num;
};
</script>

<style lang="scss" scoped>
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
::v-deep(.el-table__expand-icon) {
  display: grid;
  place-items: center;
}
:deep(.el-dialog) {
  margin-top: 10px !important;
  margin-bottom: 10px !important;
}
.con {
  font-family: "Times New Roman", "SimSun" !important;
  color: black !important;
  font-size: 12px !important;
  text-align: left;
  background-color: white;
  padding: 16px;
}
.tableOne {
  border: 1px solid black;
  line-height: 18px;
  overflow: auto;
  width: 100%;
}
.tableOne th {
  font-weight: 700;
  border-right: 1px solid black;
  text-align: center;
}
.tableOne td {
  border-right: 1px solid black;
  border-top: 1px solid black;
  text-align: center;
}
.tableTwo {
  width: 100%;
  line-height: 18px;
  word-break: break-all;
}
.tableTwo td {
  vertical-align: top;
}
.tableThree {
  width: 100%;
  line-height: 24px;
  word-break: break-all;
}
.tableThree td {
  vertical-align: top;
}
</style>
