<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" link @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="modalType == 'add' ? '添加售后记录' : '添加跟进记录'"
      v-model="dialogVisible"
      width="800"
      v-loading="submitLoading"
      destroy-on-close
    >
      <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="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;"
                    />
                  </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
      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"
          >
            <!-- <template default>
              <div>aa</div>
            </template> -->
            <div>付款金额：{{ moneyFormat(activity.amount, 2) }}</div>
            <div style="margin-top: 5px">付款时间： {{ activity.payDate }}</div>
          </el-timeline-item>
        </el-timeline>
      </div>
      <template #footer>
        <el-button @click="dialogVisibleOne = false">关闭</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: "",
  },
});
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" }],
});
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",
  },
]);
const selectConfig = computed(() => [
  {
    label: "到货状态",
    prop: "arrivalStatus",
    data: arrivalStatus.value,
  },
  {
    label: "付款状态",
    prop: "payStatus",
    data: paymentStatus.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: "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: "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: "180",
        align: "center",
        fixed: "right",
      },
    },
  ];
});

let formData = reactive({
  data: {
    type: "1",
  },
});
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",
  },
  {
    type: "number",
    prop: "amount",
    label: "付款金额",
    precision: 4,
    min: 0,
    controls: false,
  },
  {
    type: "title",
    title: "付款明细",
  },
  {
    type: "slot",
    slotName: "details",
    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();
        setTimeout(() => {
          submitLoading.value = false;
        }, 5000);
        getList();
      },
      (err) => {
        submitLoading.value = false;
      }
    );
  });
};
const selectData = ref([]);
const selectRow = (data) => {
  selectData.value = data;
};

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

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,
    })),
  };
  dialogVisible.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();
      });
  });
};

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