<template>
  <div class="tenant">
    <!-- <Banner /> -->
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :statConfig="statConfig"
        :selectConfig="selectConfig"
        :table-events="{
          //element talbe事件都能传
        }"
        :action-list="[
          {
            text: '新增采购',
            action: () => start(),
          },
        ]"
        @get-list="getList"
      >
        <template #code="{ item }">
          <div
            style="cursor: pointer; color: #409eff"
            @click="handleClickCode(item)"
          >
            {{ item.code }}
          </div>
        </template>
        <template #contractCode="{ item }">
          <div
            style="cursor: pointer; color: #409eff"
            @click="handleClickcontractCode(item)"
          >
            {{ item.contractCode }}
          </div>
        </template>
      </byTable>
    </div>
    <el-dialog
      title="到货通知"
      v-model="dialogVisible"
      width="800"
      v-loading="loading"
    >
      <el-form
        :model="formData.data"
        :rules="rules"
        ref="formDom"
        label-position="top"
      >
        <div style="margin-bottom: 10px; font-size: 14px">基础信息</div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="供应商" prop="supplyId">
              <el-select
                v-model="formData.data.supplyId"
                placeholder="请选择"
                style="width: 100%"
                disabled
              >
                <el-option
                  v-for="item in supplierData"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="采购单号" prop="code">
              <el-input
                v-model="formData.data.code"
                placeholder="请输入"
                disabled
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div style="margin-bottom: 10px; font-size: 14px">到货明细</div>
        <el-form-item>
          <el-table :data="formData.data.arrivalDetailList">
            <el-table-column
              prop="goodType"
              label="货品类型"
              :formatter="(row) => (row.goodType == 1 ? '产品' : '物料')"
            />
            <el-table-column prop="productCode" label="货品编码" />
            <el-table-column prop="productName" label="货品名称" />
            <el-table-column prop="productSpec" label="规格型号" />
            <el-table-column
              prop="productUnit"
              label="单位"
              :formatter="(row) => dictValueLabel(row.productUnit, productUnit)"
            />
            <el-table-column prop="purchaseCount" label="采购数量" />
            <el-table-column prop="sumArrivalCount" label="已到货" />
            <el-table-column prop="count" label="本次到货" min-width="150">
              <template #default="{ row, $index }">
                <el-form-item
                  :prop="'arrivalDetailList.' + $index + '.count'"
                  :rules="rules.count"
                  :inline-message="true"
                >
                  <el-input-number
                    v-model="row.count"
                    :precision="2"
                    :controls="false"
                    :min="0"
                    @change="handleChangeAmount"
                  />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm()"
          size="large"
          :loading="submitLoading"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>

    <el-dialog title="打印" v-if="openPdf" v-model="openPdf" width="840px">
      <!-- <div id="pdfDom" ref="pdfDom" style="width: 776px">
        <div style="border: 1px solid #000; border-collapse: collapse">
          <div style="text-align: right; padding: 2px 4px 0 0">
            合同号：{{ pdfData.code }}
          </div>
          <div class="title">购销合同</div>
          <div style="display: flex">
            <div style="display: flex; width: 50%; padding-right: 20px">
              <div style="width: 60px">买方：</div>
              <div style="width: calc(100% - 60px)">
                <div>福建宏星电子科技有限公司</div>
                <div>福建省福州市鼓楼区软件大道89号福州软件园A区28号楼五层</div>
              </div>
            </div>
            <div style="display: flex; width: 50%; padding-left: 20px">
              <div style="width: 60px">卖方：</div>
              <div style="width: calc(100% - 60px)">
                {{ pdfData.supplyName }}
              </div>
            </div>
          </div>
          <div style="display: flex">
            <div style="display: flex; width: 50%; padding-right: 20px">
              <div style="width: 60px">经手人：</div>
              <div style="width: calc(100% - 60px)">
                {{ pdfData.purchaseName }}
              </div>
            </div>
            <div style="display: flex; width: 50%; padding-left: 20px">
              <div style="width: 60px">经手人：</div>
              <div style="width: calc(100% - 60px)">
                {{ pdfData.contactPerson }}
              </div>
            </div>
          </div>
          <div>买卖双方经协商，一致同意签订以下合同</div>
          <div>货物名称、规格型号、单位、数量、单价及金额:</div>
          <table border="1" style="width: 100%" class="table">
            <tr>
              <td style="width: 70px">序号</td>
              <td>品名</td>
              <td>规格型号</td>
              <td style="width: 60px">单位</td>
              <td style="width: 60px">数量</td>
              <td style="width: 100px">单价</td>
              <td style="width: 100px">金额</td>
            </tr>
            <tr
              v-for="(row, index) in pdfData.purchaseDetailList"
              :key="row.id"
            >
              <td style="width: 70px">{{ index + 1 }}</td>
              <td>{{ row.productName }}</td>
              <td>{{ row.productSpec }}</td>
              <td style="width: 60px">{{ row.productUnitName }}</td>
              <td style="width: 60px">{{ row.count }}</td>
              <td style="width: 100px">
                <span v-if="pdfData.currency">{{ pdfData.currency }}</span
                >{{ row.price }}
              </td>
              <td style="width: 100px">
                <span v-if="pdfData.currency">{{ pdfData.currency }}</span
                >{{ row.amount }}
              </td>
            </tr>
            <tr>
              <td colspan="4" style="text-align: right">其他收费项目：</td>
              <td></td>
              <td></td>
              <td>
                <span v-if="pdfData.currency">{{ pdfData.currency }}</span
                >{{ pdfData.otherMoney }}
              </td>
            </tr>
            <tr>
              <td colspan="4" style="text-align: right">合计：</td>
              <td>{{ pdfData.countTotal }}</td>
              <td></td>
              <td>
                <span v-if="pdfData.currency">{{ pdfData.currency }}</span
                >{{ pdfData.amount }}
              </td>
            </tr>
            <tr>
              <td colspan="7" style="text-align: left">
                合计人民币金额（大写）：{{ pdfData.moneyChinese }}
              </td>
            </tr>
            <tr>
              <td>交货地点：</td>
              <td colspan="6" style="text-align: left">
                福建省福州市鼓楼区软件大道89号福州软件园A区28号楼五层
              </td>
            </tr>
            <tr>
              <td>保修期：</td>
              <td colspan="6" style="text-align: left">一年</td>
            </tr>
            <tr>
              <td colspan="7" style="text-align: left; padding: 0px">
                <div style="padding: 2px 0px">
                  一、交货地点：福州软件园A区28座5层。
                </div>
                <div style="padding: 2px 0px">
                  二、运输方式及运费：买方承担。
                </div>
                <div style="padding: 2px 0px">
                  三、质量要求：样品品质、型号、规格、数量如同买方确认上表规格所示，不符合则由卖方承担责任。
                </div>
                <div style="padding: 2px 0px">
                  四、交货时间：2023年4月13日。
                </div>
                <div style="padding: 2px 0px">五、付款方式：银行转账。</div>
                <div style="padding: 2px 0px">六、保修期：一年。</div>
                <div style="padding: 2px 0px">
                  七、本合同经买卖双方签字盖章后生效，传真件有效。
                </div>
                <div style="padding: 2px 0px">
                  八、解决合同纠纷：原双方另有约定外，均按《中华人民共和国合同法》有关规定处理。
                </div>
                <div style="padding: 2px 0px">九、其他约定事项：友好解决。</div>
              </td>
            </tr>
          </table>
          <div style="display: flex">
            <div style="width: 50%; padding-right: 20px">
              <div>买方：</div>
              <div>单位名称：福建宏星电子科技有限公司</div>
              <div>
                地址：福建省福州市鼓楼区软件大道89号福州软件园A区28号楼五层
              </div>
              <div>电话：</div>
              <div>传真：</div>
              <div style="opacity: 0">|</div>
              <div style="margin-top: auto">代表人签字：</div>
            </div>
            <div style="width: 50%; padding-left: 20px">
              <div>卖方：</div>
              <div>单位名称：{{ pdfData.supplyName }}</div>
              <div>统一社会信用代码：</div>
              <div>开户银行：{{ pdfData.openingBank }}</div>
              <div>帐号：{{ pdfData.accountOpening }}</div>
              <div>
                地址：<span
                  v-if="
                    pdfData.supplyAddress && pdfData.supplyAddress.countryName
                  "
                  >{{ pdfData.supplyAddress.countryName }}</span
                >
                <span
                  v-if="
                    pdfData.supplyAddress && pdfData.supplyAddress.provinceName
                  "
                  >,{{ pdfData.supplyAddress.provinceName }}</span
                >
                <span
                  v-if="pdfData.supplyAddress && pdfData.supplyAddress.cityName"
                  >,{{ pdfData.supplyAddress.cityName }}</span
                >
                <span
                  v-if="
                    pdfData.supplyAddress && pdfData.supplyAddress.areaDetail
                  "
                  >,{{ pdfData.supplyAddress.areaDetail }}</span
                >
              </div>
              <div>电话：{{ pdfData.contactNumber }}</div>
              <div>代表人签字：</div>
            </div>
          </div>
          <div
            style="
              padding: 30px 0px 20px 0;
              text-align: right;
              border-top: 1px solid #000;
            "
          >
            签订日期：{{ pdfData.approvedDate }}
          </div>
        </div>
      </div> -->
      <PurchasePDF :rowData="rowData"></PurchasePDF>
      <template #footer ref="printBtn">
        <el-button @click="openPdf = false" size="large">关闭</el-button>
        <el-button type="primary" v-print="printObj" size="large"
          >打印</el-button
        >
        <el-button type="primary" @click="clickDownload()" size="large"
          >下载PDF</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import { NumberToChinese } from "@/utils/util.js";
import PurchasePDF from "@/components/PDF/purchasePDF.vue";

const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
  },
});
let dialogVisible = ref(false);
let modalType = ref("add");
let rules = ref({
  count: [{ required: true, message: "请输入本次到货", trigger: "blur" }],
});
const { proxy } = getCurrentInstance();
const statusData = ref([
  {
    label: "审批中",
    value: "10",
  },
  {
    label: "驳回",
    value: "20",
  },
  {
    label: "已采购",
    value: "30",
  },
  {
    label: "终止",
    value: "99",
  },
  {
    label: "已作废",
    value: "88",
  },
]);
const arrivalStatus = ref([
  {
    label: "未到货",
    value: "0",
  },
  {
    label: "部分到货",
    value: "10",
  },
  {
    label: "已到货",
    value: "20",
  },
]);
const paymentStatus = ref([
  {
    label: "未付款",
    value: "0",
  },
  {
    label: "部分付款",
    value: "10",
  },
  {
    label: "已付款",
    value: "20",
  },
]);
const headerData = ref({
  sumOrderCount: 0,
  sumPurchaseMoney: 0,
  noArrivalOrderCount: 0,
  noArrivalPurchaseMoney: 0,
  partArrivalOrderCount: 0,
  partArrivalPurchaseMoney: 0,
  alArrivalPurchaseMoney: 0,
  alArrivalOrderCount: 0,
});
const getHeaderData = () => {
  proxy.post("/purchase/statisticsPurchaseHead").then((res) => {
    headerData.value = res;
  });
};

const statConfig = computed(() => [
  {
    label: "统计",
    data: [
      //一个卡牌多数据配置
      {
        label: "合计",
        type: 2,
        data: [
          {
            label: "订单数",
            num: headerData.value.sumOrderCount,
            color: "#C280FF",
          },
          {
            label: "采购金额",
            num: proxy.moneyFormat(headerData.value.sumPurchaseMoney, 2),
            color: "#C280FF",
          },
        ],
      },
      {
        label: "未到货",
        data: [
          {
            label: "订单数",
            num: headerData.value.noArrivalOrderCount,
            color: "#0084FF",
          },
          {
            label: "采购金额",
            num: proxy.moneyFormat(headerData.value.noArrivalPurchaseMoney, 2),
            color: "#0084FF",
          },
        ],
      },
      {
        label: "部分到货",
        data: [
          {
            label: "订单数",
            num: headerData.value.partArrivalOrderCount,
            color: "#0084FF",
          },
          {
            label: "采购金额",
            num: proxy.moneyFormat(
              headerData.value.partArrivalPurchaseMoney,
              2
            ),
            color: "#0084FF",
          },
        ],
      },
      {
        label: "已到货",
        data: [
          {
            label: "订单数",
            num: headerData.value.alArrivalOrderCount,
            color: "#0084FF",
          },
          {
            label: "采购金额",
            num: proxy.moneyFormat(headerData.value.alArrivalPurchaseMoney, 2),
            color: "#0084FF",
          },
        ],
      },
    ],
  },
]);
const selectConfig = reactive([
  {
    label: "采购状态",
    prop: "purchaseStatus",
    data: statusData.value,
  },
  {
    label: "到货状态",
    prop: "arrivalStatus",
    data: arrivalStatus.value,
  },
  {
    label: "付款状态",
    prop: "payStatus",
    data: paymentStatus.value,
  },
]);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "采购单号",
        prop: "code",
        slot: "code",
      },
    },
    {
      attrs: {
        label: "关联销售合同",
        prop: "contractCode",
        slot: "contractCode",
      },
    },
    {
      attrs: {
        label: "供应商",
        prop: "supplyName",
      },
    },

    {
      attrs: {
        label: "采购金额",
        prop: "amount",
        width: 120,
      },
      render(amount) {
        return proxy.moneyFormat(amount, 2);
      },
    },
    {
      attrs: {
        label: "已付款金额（CNY）",
        prop: "paySumAmount",
        width: 160,
      },
      render(amount) {
        return proxy.moneyFormat(amount, 2);
      },
    },
    {
      attrs: {
        label: "采购人",
        prop: "purchaseName",
      },
    },
    {
      attrs: {
        label: "采购时间",
        prop: "createTime",
        width: 155,
      },
    },
    {
      attrs: {
        label: "采购状态",
        prop: "purchaseStatus",
        width: 80,
      },
      render(status) {
        return proxy.dictValueLabel(status, statusData.value);
      },
    },

    {
      attrs: {
        label: "到货状态",
        prop: "arrivalStatus",
        width: 80,
      },
      render(status) {
        return proxy.dictValueLabel(status, arrivalStatus.value);
      },
    },
    {
      attrs: {
        label: "付款状态",
        prop: "payStatus",
        width: 80,
      },
      render(status) {
        return proxy.dictValueLabel(status, paymentStatus.value);
      },
    },
    {
      attrs: {
        label: "操作",
        width: "250",
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "打印",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              handlePrintPdf(row);
            },
          },
          row.purchaseStatus == 30
            ? {
                attrs: {
                  label: "到货通知",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  handleArrival(row);
                },
              }
            : {},
          row.purchaseStatus != 88
            ? {
                attrs: {
                  label: "作废",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  handleEditOne(row);
                },
              }
            : {},
          {
            attrs: {
              label: "终止",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              handleEdit(row, 99);
            },
          },
        ];
      },
    },
  ];
});

let formData = reactive({
  data: {
    type: "1",
  },
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formDom = ref(null);
const formConfig = computed(() => {
  return [
    {
      type: "radio",
      prop: "name",
      label: "供应商类型",
      required: true,
      border: true,
      data: [
        { label: "贸易商", value: "1" },
        { label: "工厂", value: "2" },
      ],
    },
    {
      type: "input",
      prop: "name",
      label: "供应商名称",
      required: true,
    },
    {
      type: "slot",
      slotName: "address",
      label: "地址",
      required: true,
    },
    {
      type: "slot",
      slotName: "contact",
      label: "联系信息",
      required: true,
    },
    {
      type: "slot",
      slotName: "fileSlot",
      label: "上传附件",
    },
    {
      type: "input",
      label: "备注",
      prop: "remakes",
      itemType: "textarea",
    },
  ];
});
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/purchase/page", sourceList.value.pagination).then((message) => {
    console.log(message);
    sourceList.value.data = message.rows;
    sourceList.value.pagination.total = message.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};

const submitForm = async () => {
  formDom.value.validate((vaild) => {
    if (vaild) {
      const list = formData.data.arrivalDetailList;
      const total = list.reduce((total, x) => (total += Number(x.count)), 0);
      if (!(total > 0)) {
        return ElMessage({
          message: `本次到货不能为0！`,
          type: "info",
        });
      }
      let sum = 0;
      for (let i = 0; i < list.length; i++) {
        const e = list[i];
        delete e.id;
        if (
          Number(e.sumArrivalCount) + Number(e.count) >=
          Number(e.purchaseCount)
        ) {
          sum += 1;
        }
      }
      formData.data.arrivalStatus = sum === list.length ? "20" : "10";
      proxy.post("/arrival/add", formData.data).then((res) => {
        ElMessage({
          message: `操作成功！`,
          type: "success",
        });
        dialogVisible.value = false;
        getList();
      });
    }
  });
};

const getDtl = (row) => {
  modalType.value = "edit";
  proxy.post("/productionProcesses/detail", { id: row.id }).then((res) => {
    formData.data = res;
    dialogVisible.value = true;
  });
};

const handleEdit = (row, status) => {
  let purchaseStatusName = status == 88 ? "作废" : "终止";
  const data = { ...row, purchaseStatus: status };
  // 弹窗提示是否删除
  ElMessageBox.confirm(
    `此操作将${purchaseStatusName}该数据, 是否继续?`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    // 删除
    proxy.post("/purchase/edit", data).then((res) => {
      ElMessage({
        message: `${purchaseStatusName}成功`,
        type: "success",
      });
      getList();
    });
  });
};

const handleEditOne = (row) => {
  const data = { id: row.id, purchaseStatus: 88 };
  // 弹窗提示是否删除
  ElMessageBox.confirm(`此操作将作废该数据, 是否继续?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 删除
    proxy.post("/sale/purchase/cancellation", data).then((res) => {
      ElMessage({
        message: `作废成功`,
        type: "success",
      });
      getList();
    });
  });
};

const supplierData = ref([]);
const productUnit = ref([]);
const getDict = async (req) => {
  proxy
    .post("/supplierInfo/page", { pageNum: 1, pageSize: 9999 })
    .then((res) => {
      supplierData.value = res.rows;
    });
  proxy.getDictOne(["unit"]).then((res) => {
    productUnit.value = res["unit"].map((x) => ({
      label: x.dictValue,
      value: x.dictKey,
    }));
  });
};
const handleArrival = (row) => {
  proxy.post("/purchase/detail", { id: row.id }).then((res) => {
    formData.data = {
      purchaseId: row.id,
      code: res.code,
      supplyId: res.supplyId,
      arrivalDetailList: res.purchaseDetailList.map((x) => {
        let obj = {
          ...x,
          purchaseDetailId: x.id,
          purchaseCount: x.count,
          count: Number(x.count) - Number(x.sumArrivalCount),
        };
        delete obj.status;
        return obj;
      }),
      arrivalStatus: "",
    };
    dialogVisible.value = true;
  });
};

getDict();
getHeaderData();
getList();

const start = () => {
  proxy.$router.replace({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: "purchase_flow",
      ids: "",
      flowName: "采购申请",
      random: proxy.random(),
    },
  });
};

const handleClickCode = (row) => {
  proxy.$router.push({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: row.processInstanceId,
      id: row.flowId,
      processType: 20,
    },
  });
};

const handleClickcontractCode = (row) => {
  proxy.$router.push({
    name: "Contract",
    query: {
      code: row.contractCode,
    },
  });
};

const openPdf = ref(false);
const pdfData = ref({});
const rowData = ref({});
const handlePrintPdf = (row) => {
  rowData.value = {
    id: row.id,
    code: row.code,
  };
  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"/>',
});
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
#pdfDom {
  font-size: 12px;
  color: #000000;
  padding: 60px 30px;
  .title {
    font-size: 16px;
    font-weight: 700;
    margin-top: 10px;
    margin-bottom: 20px;
    text-align: center;
  }
  .table {
    // width: calc(100% + 2px) !important;
    border-collapse: collapse;
    border-spacing: 0;
    // margin-left: -1px;
    // margin-right: -1px;

    td {
      text-align: center;
      padding: 8px 0px;
    }
    // tr td:last-child {
    //   border-right: 0 !important;
    // }
  }
  .flex-top-bottom {
    display: flex;
    justify-content: space-between;
    margin: 5px 0px;
  }
}
</style>