<template>
  <div class="tenant">
    <!-- <Banner /> -->
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :selectConfig="selectConfig"
        :table-events="{
          //element talbe事件都能传
          select: selectRow,
        }"
        :action-list="[
          {
            text: '合并付款',
            disabled: selectData.length === 0,
            action: () => handlePayment(20),
          },
        ]"
        @get-list="getList"
      >
        <template #contractCode="{ item }">
          <div
            style="cursor: pointer; color: #409eff"
            @click="handleClickContractCode(item)"
          >
            {{ item.contractCode }}
          </div>
        </template>

        <template #payStatus="{ item }">
          <div
            style="cursor: pointer; color: #409eff"
            @click="handleClickPayStatus(item)"
          >
            {{ dictValueLabel(item.payStatus, paymentStatus) }}
          </div>
        </template>

        <template #btn="{ item }">
          <div>
            <el-button
              type="primary"
              v-if="item.payStatus != 0"
              link
              @click="handleRefund(item)"
              >退款</el-button
            >
            <el-button
              type="primary"
              link
              v-if="item.payStatus != 30"
              @click="handlePayment(10, item)"
              >付款</el-button
            >
            <el-button
              type="primary"
              link
              v-if="item.payStatus != 30"
              @click="handleEnd(item)"
              >结束</el-button
            >
            <el-button type="primary" link @click="handleClear(item)"
              >清空</el-button
            >
          </div>
        </template>
      </byTable>
    </div>
    <el-dialog
      :title="'付款'"
      v-model="dialogVisible"
      width="80%"
      v-loading="submitLoading"
      destroy-on-close
      :before-close="handleClose"
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="byform"
      >
        <template #details>
          <div style="width: 100%">
            <el-table :data="formData.data.purchasePayRecordDetailList">
              <el-table-column prop="code" label="采购单号" />
              <el-table-column
                prop="isAgreement"
                label="是否合同"
                :formatter="(row) => (row.isAgreement == 1 ? '是' : '否')"
              />
              <el-table-column
                prop="paymentMethod"
                label="付款方式"
                :formatter="
                  (row) => dictValueLabel(row.paymentMethod, fundsPaymentMethod)
                "
              />
              <el-table-column prop="remark" label="采购备注" />
              <el-table-column prop="waitAmount" label="采购金额" />
              <el-table-column prop="alreadyAmount" label="已付款金额" />
              <el-table-column prop="amount" label="付款金额" min-width="150">
                <template #default="{ row, $index }">
                  <el-form-item
                    :prop="'purchasePayRecordDetailList.' + $index + '.amount'"
                    :rules="rules.amount"
                    :inline-message="true"
                  >
                    <el-input-number
                      v-model="row.amount"
                      :precision="4"
                      :controls="false"
                      :min="0"
                      onmousewheel="return false;"
                      @change="handleChangeAmount"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注" min-width="150">
                <template #default="{ row, $index }">
                  <el-form-item
                    :prop="'purchasePayRecordDetailList.' + $index + '.remark'"
                    :rules="rules.remark"
                    :inline-message="true"
                  >
                    <el-input
                      v-model="row.remark"
                      placeholder="请输入"
                      type="textarea"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="handleClose" size="large">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm('byform')"
          size="large"
          :loading="submitLoading"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>
    <el-dialog
      :title="'退款'"
      v-model="dialogVisibleTwo"
      width="800"
      v-loading="submitLoading"
      destroy-on-close
    >
      <byForm
        :formConfig="formConfigOne"
        :formOption="formOption"
        v-model="formData.dataOne"
        :rules="rulesOne"
        ref="byformOne"
      >
      </byForm>
      <template #footer>
        <el-button @click="dialogVisibleTwo = false" size="large"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="submitFormOne()"
          size="large"
          :loading="submitLoading"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="dialogVisibleOne"
      title="付款记录"
      width="500"
      append-to-body
      destroy-on-close
    >
      <div>
        <el-timeline :reverse="false">
          <el-timeline-item
            placement="top"
            v-for="(activity, index) in activities"
            :key="index"
            :timestamp="activity.payUserName"
          >
            <div>
              付款账号： {{ dictValueLabel(activity.payAccount, accountData) }}
            </div>
            <div style="margin-top: 5px">
              付款金额：{{ moneyFormat(activity.amount, 2) }}
            </div>
            <div style="margin-top: 5px">付款时间： {{ activity.payDate }}</div>
            <div style="margin-top: 5px">付款备注： {{ activity.remark }}</div>
          </el-timeline-item>
        </el-timeline>
      </div>
      <template #footer>
        <el-button @click="dialogVisibleOne = false">关闭</el-button>
      </template>
    </el-dialog>

    <el-dialog
      :title="'到货详情'"
      v-model="dialogVisibleThree"
      width="80%"
      destroy-on-close
    >
      <byForm
        :formConfig="formConfigTwo"
        :formOption="formOption"
        v-model="formData.dataTwo"
        :rules="rules"
        ref="byformOne"
      >
        <template #detailSlot>
          <div style="width: 100%">
            <el-table :data="formData.dataTwo.purchaseDetailVoList">
              <el-table-column prop="productCustomCode" label="物品编码" />
              <el-table-column prop="productName" label="物品名称" />
              <el-table-column prop="count" label="采购数量" />
              <el-table-column prop="deliverGoodsQuantity" label="已发货">
                <template #default="{ row }">
                  <div>
                    <el-popover
                      placement="bottom-start"
                      title="发货详情"
                      :width="500"
                      trigger="hover"
                    >
                      <div default>
                        <el-table :data="row.deliverGoodsDetailList">
                          <el-table-column
                            label="发货时间"
                            prop="createTime"
                            width="155"
                          />
                          <el-table-column
                            label="物流单号"
                            prop="logisticsCode"
                          />
                          <el-table-column
                            label="数量"
                            prop="deliverGoodsQuantity"
                            width="100"
                          />
                        </el-table>
                      </div>
                      <template #reference>
                        <div style="cursor: pointer; color: #0084ff">
                          {{ row.deliverGoodsQuantity }}
                        </div>
                      </template>
                    </el-popover>
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="receiptQuantity" label="已入库">
                <template #default="{ row }">
                  <div>
                    <el-popover
                      placement="bottom-start"
                      title="入库详情"
                      :width="500"
                      trigger="hover"
                    >
                      <div default>
                        <el-table :data="row.receiptList">
                          <el-table-column
                            label="入库时间"
                            prop="createTime"
                            width="155"
                          />
                          <el-table-column
                            label="入库单号"
                            prop="logisticsCode"
                          />
                          <el-table-column
                            label="数量"
                            prop="quantity"
                            width="100"
                          />
                        </el-table>
                      </div>
                      <template #reference>
                        <div style="cursor: pointer; color: #0084ff">
                          {{ row.receiptQuantity }}
                        </div>
                      </template>
                    </el-popover>
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="purchaseBackQuantity" label="退货">
                <template #default="{ row }">
                  <div>
                    <el-popover
                      placement="bottom-start"
                      title="退货详情"
                      :width="500"
                      trigger="hover"
                    >
                      <div default>
                        <el-table :data="row.purchaseBackDetailsList">
                          <el-table-column label="申请时间" prop="createTime" />
                          <el-table-column label="申请数量" prop="quantity" />
                          <el-table-column
                            label="已退数量"
                            prop="returnedQuantity"
                          />
                        </el-table>
                      </div>
                      <template #reference>
                        <div style="cursor: pointer; color: #0084ff">
                          {{ row.purchaseBackQuantity }}
                        </div>
                      </template>
                    </el-popover>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="qualityQuantity" label="已质检数量" />
              <el-table-column prop="noQualifiedCount" label="不合格数量" />
            </el-table>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisibleThree = false" size="large"
          >取 消</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";

const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
    type: "",
    keyword: "",
    purchaseStatus: "30,99",
  },
});
let dialogVisible = ref(false);
let dialogVisibleOne = ref(false);
let activities = ref([]);
let modalType = ref("add");
let rules = ref({
  amount: [{ required: true, message: "请输入付款金额", trigger: "blur" }],
  payDate: [{ required: true, message: "请选择付款时间", trigger: "change" }],
  payAccount: [
    { required: true, message: "请选择付款账号", trigger: "change" },
  ],
});
let rulesOne = ref({
  amount: [{ required: true, message: "请输入退款金额", trigger: "blur" }],
  refundDate: [
    { required: true, message: "请选择退款时间", trigger: "change" },
  ],
  refundAccount: [
    { required: true, message: "请选择退款账号", trigger: "change" },
  ],
  // remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
});
const { proxy } = getCurrentInstance();
const arrivalStatus = ref([
  {
    label: "未到货",
    value: "0",
  },
  {
    label: "部分到货",
    value: "10",
  },
  {
    label: "已到货",
    value: "20",
  },
]);
const paymentStatus = ref([
  {
    label: "未付款",
    value: "0",
  },
  {
    label: "部分付款",
    value: "10",
  },
  {
    label: "已付款",
    value: "20",
  },
  {
    label: "付款结束",
    value: "30",
  },
]);
const alreadyPurchase = ref([]);
const deptData = ref([]);
const selectConfig = computed(() => [
  {
    label: "到货状态",
    prop: "arrivalStatus",
    data: arrivalStatus.value,
  },
  {
    label: "付款状态",
    prop: "payStatus",
    data: paymentStatus.value,
  },
  {
    label: "采购人",
    prop: "purchaseUserId",
    data: alreadyPurchase.value,
  },
  {
    label: "项目组",
    prop: "deptId",
    data: deptData.value,
  },
]);
const config = computed(() => {
  return [
    {
      type: "selection",
      attrs: {
        checkAtt: "isCheck",
      },
    },
    {
      attrs: {
        label: "采购单号",
        slot: "contractCode",
      },
    },
    {
      attrs: {
        label: "供应商",
        prop: "supplyName",
      },
    },
    {
      attrs: {
        label: "收货仓库",
        prop: "receiptWarehouseName",
      },
    },
    {
      attrs: {
        label: "项目组",
        prop: "deptName",
        width: 150,
      },
    },
    {
      attrs: {
        label: "采购金额",
        prop: "amount",
        width: 100,
      },
      render(amount) {
        return proxy.moneyFormat(amount, 2);
      },
    },
    {
      attrs: {
        label: "已付款金额",
        prop: "paidAmount",
        width: 100,
      },
      render(paidAmount) {
        return proxy.moneyFormat(paidAmount, 2);
      },
    },
    {
      attrs: {
        label: "退款金额",
        prop: "refundAmount",
        width: 100,
      },
      render(refundAmount) {
        return proxy.moneyFormat(refundAmount, 2);
      },
    },
    {
      attrs: {
        label: "采购人",
        prop: "purchaseName",
        width: 150,
      },
    },
    {
      attrs: {
        label: "采购时间",
        prop: "createTime",
        width: 155,
      },
    },
    {
      attrs: {
        label: "到货状态",
        prop: "arrivalStatus",
        width: 100,
      },
      render(status) {
        return proxy.dictValueLabel(status, arrivalStatus.value);
      },
    },
    {
      attrs: {
        label: "付款状态",
        slot: "payStatus",
        width: 100,
      },
    },
    {
      attrs: {
        label: "操作",
        slot: "btn",
        width: "200",
        align: "center",
        fixed: "right",
      },
    },
  ];
});

let formData = reactive({
  data: {
    type: "1",
  },
  dataOne: {},
  dataTwo: {},
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
let formConfig = computed(() => [
  {
    type: "input",
    prop: "supplyName",
    label: "供应商",
    disabled: true,
  },
  {
    type: "date",
    itemType: "datetime",
    prop: "payDate",
    label: "付款时间",
    format: "YYYY-MM-DD HH:mm:ss",
    itemWidth: 35,
  },
  {
    type: "select",
    prop: "payAccount",
    label: "付款账号",
    data: accountData.value,
    itemWidth: 50,
  },
  {
    type: "number",
    prop: "amount",
    label: "付款金额",
    precision: 4,
    min: 0,
    controls: false,
    disabled: true,
  },
  {
    type: "input",
    itemType: "textarea",
    prop: "remark",
    label: "备注",
    disabled: false,
  },
  {
    type: "title",
    title: "付款明细",
  },
  {
    type: "slot",
    slotName: "details",
    label: "",
  },
]);
const dialogVisibleTwo = ref(false);
const dialogVisibleThree = ref(false);

const byformOne = ref(null);
let formConfigOne = computed(() => [
  {
    type: "input",
    prop: "supplyName",
    label: "供应商",
    disabled: true,
  },
  {
    type: "input",
    prop: "contractCode",
    label: "采购单号",
    disabled: true,
    itemWidth: 34,
  },
  {
    type: "date",
    itemType: "datetime",
    prop: "refundDate",
    label: "退款时间",
    format: "YYYY-MM-DD HH:mm:ss",
    itemWidth: 100,
  },
  {
    type: "select",
    prop: "refundAccount",
    label: "退款账号",
    data: accountData.value,
    itemWidth: 100,
  },
  {
    type: "number",
    prop: "amount",
    label: "退款金额",
    precision: 4,
    min: 1,
    controls: false,
    // disabled: true,
  },
  {
    type: "input",
    itemType: "textarea",
    prop: "remark",
    label: "备注",
    disabled: false,
  },
]);
let formConfigTwo = computed(() => [
  {
    type: "title",
    title: "基础信息",
  },
  {
    type: "input",
    prop: "supplyName",
    label: "供应商",
    disabled: true,
    itemWidth: 50,
  },
  {
    type: "input",
    prop: "purchaseCode",
    label: "采购单号",
    disabled: true,
    itemWidth: 50,
  },
  {
    type: "title",
    title: "采购明细",
  },
  {
    type: "slot",
    slotName: "detailSlot",
    label: "",
  },
]);
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/purchase/pageByWdly", sourceList.value.pagination)
    .then((res) => {
      sourceList.value.data = res.rows.map((x) => ({
        ...x,
        ...JSON.parse(x.victoriatouristJson),
        isCheck: true,
      }));
      sourceList.value.pagination.total = res.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};
const submitForm = () => {
  byform.value.handleSubmit((valid) => {
    const list = formData.data.purchasePayRecordDetailList;
    for (let i = 0; i < list.length; i++) {
      const e = list[i];
      if (Number(e.amount) + Number(e.alreadyAmount) > Number(e.waitAmount)) {
        return ElMessage({
          message: `本次付款加已付款金额不可大于采购金额`,
          type: "info",
        });
      }
    }
    // const total = list.reduce((total, x) => (total += Number(x.amount)), 0);
    // if (Number(formData.data.amount) != total) {
    //   return ElMessage({
    //     message: "本次付款合计必须等于上方的付款金额",
    //     type: "info",
    //   });
    // }
    proxy.post("/purchasePayRecord/add", formData.data).then(
      (res) => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        handleClose();
        submitLoading.value = false;
        getList();
      },
      (err) => {
        submitLoading.value = false;
      }
    );
  });
};

const submitFormOne = () => {
  byformOne.value.handleSubmit((valid) => {
    submitLoading.value = true;
    proxy.post("/purchaseRefundRecord/add", formData.dataOne).then(
      (res) => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        dialogVisibleTwo.value = false;
        submitLoading.value = false;
        getList();
      },
      (err) => {
        submitLoading.value = false;
      }
    );
  });
};
const selectData = ref([]);
const selectRow = (data) => {
  if (data && data.length > 0) {
    selectData.value = data.map((x) => {
      if (x.victoriatouristJson) {
        let obj = JSON.parse(x.victoriatouristJson);
        if (obj.isAgreement) {
          x.isAgreement = obj.isAgreement;
        }
        if (obj.paymentMethod) {
          x.paymentMethod = obj.paymentMethod;
        }
      }
      return x;
    });
  } else {
    selectData.value = [];
  }
};

const handleClose = () => {
  selectData.value = [];
  dialogVisible.value = false;
};

watch(selectData, (newVal, oldVal) => {
  if (newVal.length == 0) {
    sourceList.value.data.forEach((x) => {
      x.isCheck = true;
    });
  } else if (newVal.length == 1) {
    const current = newVal[0];
    sourceList.value.data.forEach((x) => {
      if (x.supplyId !== current.supplyId) {
        x.isCheck = false;
      }
    });
  }
});
const handlePayment = (type, data) => {
  modalType.value = "add";
  if (type === 10) {
    selectData.value = [data];
  } else if (type === 20) {
  }
  formData.data = {
    supplyName: selectData.value[0].supplyName,
    amount: "",
    payDate: "",
    purchasePayRecordDetailList: selectData.value.map((x) => ({
      purchaseId: x.id,
      code: x.contractCode,
      waitAmount: x.amount,
      alreadyAmount: x.paidAmount,
      amount: null,
      remark: "",
      isAgreement: x.isAgreement,
      paymentMethod: x.paymentMethod,
      remark: x.remark,
    })),
  };
  dialogVisible.value = true;
};

const handleRefund = (row) => {
  formData.dataOne = {
    purchaseId: row.id,
    supplyName: row.supplyName,
    contractCode: row.contractCode,
    amount: "",
    refundDate: "",
    remark: "",
  };
  dialogVisibleTwo.value = true;
};

const handleClickPayStatus = (row) => {
  proxy
    .post("/purchasePayRecordDetail/page", { purchaseId: row.id })
    .then((res) => {
      if (res && res.rows && res.rows.length > 0) {
        activities.value = res.rows;
        dialogVisibleOne.value = true;
      } else {
        return ElMessage({
          message: `暂无付款记录`,
          type: "info",
        });
      }
    });
};

const handleEnd = (row) => {
  // 弹窗提示是否删除
  ElMessageBox.confirm("是否确认结束?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 删除
    proxy
      .post("/purchase/edit", {
        ...row,
        payStatus: 30,
      })
      .then((res) => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        getList();
      });
  });
};

const handleClear = (row) => {
  // 弹窗提示是否删除
  ElMessageBox.confirm("是否确认清空付款记录?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 删除
    proxy
      .post("/purchasePayRecordDetail/empty", {
        purchaseId: row.id,
      })
      .then((res) => {
        ElMessage({
          message: "操作成功",
          type: "success",
        });
        getList();
      });
  });
};

const handleChangeAmount = () => {
  let amount = 0;
  for (let i = 0; i < formData.data.purchasePayRecordDetailList.length; i++) {
    const e = formData.data.purchasePayRecordDetailList[i];
    amount += e.amount;
  }
  formData.data.amount = parseFloat(amount).toFixed(4);
};
const accountData = ref([]);
const fundsPaymentMethod = ref([]);
const getDict = () => {
  proxy.get("/purchase/getPurchaseUserList").then((res) => {
    alreadyPurchase.value = res.data.map((x) => ({
      label: x.nickName,
      value: x.userId,
    }));
  });
  proxy.get("/purchase/getDepts").then((res) => {
    deptData.value = res.data.map((x) => ({
      ...x,
      label: x.deptName,
      value: x.deptId,
    }));
  });

  proxy
    .getDictOne(["purchase_payment_account", "funds_payment_method"])
    .then((res) => {
      accountData.value = res["purchase_payment_account"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
      fundsPaymentMethod.value = res["funds_payment_method"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
    });
};

const handleClickContractCode = (row) => {
  // proxy
  //   .post("/deliverGoods/arrivalDetail", { purchaseId: row.id })
  //   .then((res) => {
  //     formData.dataTwo = {
  //       supplyName: row.supplyName,
  //       purchaseCode: row.contractCode,
  //       purchaseDetailVoList: res.purchaseDetailVoList,
  //     };
  //     dialogVisibleThree.value = true;
  //   });
  proxy.$router.push({
    path: "/platform_manage/process/processApproval",
    query: {
      flowKey: row.processInstanceId,
      id: row.flowId,
      businessId: row.id,
      processType: 20,
    },
  });
};

getList();
getDict();
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
:deep(.el-table__header-wrapper .el-checkbox) {
  display: none;
}
</style>