<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事件都能传
        }"
        :action-list="[]"
        @get-list="getList"
      >
        <template #fileSlot="{ item }">
          <div
            style="cursor: pointer; color: #409eff"
            @click="handleClickFile(item)"
          >
            {{ item.fileName }}
          </div>
        </template>
      </byTable>
    </div>
    <el-dialog
      :title="modalType === 'add' ? '发货登记' : '到货通知'"
      v-model="dialogVisible"
      width="800"
      v-loading="loading"
      destroy-on-close
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="byform"
      >
        <template #detailSlot>
          <div style="width: 100%">
            <el-table
              :data="
                modalType === 'add'
                  ? formData.data.deliverGoodsDetailsList
                  : formData.data.arrivalDetailList
              "
            >
              <el-table-column
                prop="productDefinition"
                label="物品类型"
                :formatter="
                  (row) =>
                    row.productDefinition == 1
                      ? '产品'
                      : row.productDefinition == 2
                      ? '物料'
                      : ''
                "
              />

              <el-table-column prop="productCode" label="物品编码" />
              <el-table-column prop="productName" label="物品名称" />
              <el-table-column prop="productSpec" label="规格型号" />
              <el-table-column prop="productUnit" label="单位" />
              <el-table-column prop="count" label="采购数量" />
              <el-table-column
                prop="alreadyDeliverGoodsQuantity"
                label="累计发货"
                v-if="modalType === 'add'"
              />
              <el-table-column
                prop="deliverGoodsQuantity"
                label="本次发货"
                min-width="150"
                v-if="modalType === 'add'"
              >
                <template #default="{ row, $index }">
                  <el-form-item
                    :prop="
                      'deliverGoodsDetailsList.' +
                      $index +
                      '.deliverGoodsQuantity'
                    "
                    :rules="rules.deliverGoodsQuantity"
                    :inline-message="true"
                  >
                    <el-input-number
                      v-model="row.deliverGoodsQuantity"
                      :precision="4"
                      :controls="false"
                      :min="0"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="transitQuantity"
                label="剩余在途"
                v-if="modalType === 'edit'"
              />
              <el-table-column
                prop="deliverGoodsQuantity"
                label="本次到货"
                v-if="modalType === 'edit'"
              />
            </el-table>
          </div>
        </template>
      </byForm>

      <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>
  </div>
</template>
  
<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import { watch } from "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({
  deliverGoodsId: [
    { required: true, message: "请选择快递单号", trigger: "change" },
  ],
  logisticsCompanyCode: [
    { required: true, message: "请选择物流公司", trigger: "change" },
  ],
  code: [{ required: true, message: "请输入物流/快递单号", trigger: "blur" }],
  deliverGoodsQuantity: [
    { required: true, message: "请输入本次发货", trigger: "blur" },
  ],
});
const { proxy } = getCurrentInstance();
const arrivalStatus = [
  {
    label: "未到货",
    value: "0",
  },
  {
    label: "部分到货",
    value: "1",
  },
  {
    label: "已到货",
    value: "2",
  },
];
const statusData = ref([
  {
    label: "审批中",
    value: "10",
  },
  {
    label: "待采购",
    value: "15",
  },
  {
    label: "部分采购",
    value: "30",
  },
  {
    label: "已采购",
    value: "20",
  },
  {
    label: "已作废",
    value: "99",
  },
]);
const selectConfig = reactive([
  {
    label: "采购状态",
    prop: "purchaseStatus",
    data: statusData.value,
  },
  {
    label: "到货状态",
    prop: "arrivalStatus",
    data: arrivalStatus,
  },
  {
    label: "付款状态",
    prop: "payStatus",
    data: [
      {
        label: "未付款",
        value: "1",
      },
      {
        label: "部分付款",
        value: "2",
      },
      {
        label: "已付款",
        value: "3",
      },
    ],
  },
]);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "采购单号",
        prop: "code",
      },
    },
    {
      attrs: {
        label: "供应商",
        prop: "supplyName",
      },
    },
    {
      attrs: {
        label: "收货仓库",
        prop: "receiptWarehouseName",
      },
    },
    {
      attrs: {
        label: "采购金额",
        prop: "amount",
      },
      render(amount) {
        return proxy.moneyFormat(amount, 2);
      },
    },
    {
      attrs: {
        label: "采购人",
        prop: "purchaseName",
      },
    },
    {
      attrs: {
        label: "采购时间",
        prop: "createTime",
      },
    },
    {
      attrs: {
        label: "采购状态",
        prop: "purchaseStatus",
      },
      render(status) {
        const current = statusData.value.find((x) => x.value == status);
        if (current) return current.label;
      },
    },
    {
      attrs: {
        label: "到货状态",
        prop: "arrivalStatus",
      },
      render(status) {
        return arrivalStatus.find((x) => x.value == status).label;
      },
    },
    {
      attrs: {
        label: "付款状态",
        prop: "payStatus1",
      },
    },
    {
      attrs: {
        label: "操作",
        width: "240",
        align: "right",
      },
      renderHTML(row) {
        return [
          //  (row.purchaseStatus == 20 || row.purchaseStatus == 30) &&
          // row.arrivalStatus != 2
          //   ?
          {
            attrs: {
              label: "发货登记",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              handleArrival(row, "add");
            },
          },
          {
            attrs: {
              label: "到货通知",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              handleArrival(row, "edit");
            },
          },
          {
            attrs: {
              label: "作废",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              handleEdit(row, 88);
            },
          },
          {
            attrs: {
              label: "终止",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              handleEdit(row, 99);
            },
          },
        ];
      },
    },
  ];
});

let formData = reactive({
  data: {},
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
});
const byform = ref(null);
let formConfig = reactive([]);
const configData = [
  [
    {
      type: "title",
      title: "基础信息",
    },
    {
      type: "input",
      prop: "supplyName",
      label: "供应商",
      disabled: true,
      itemWidth: 50,
    },
    {
      type: "input",
      prop: "purchaseCode",
      label: "采购单号",
      disabled: true,
      itemWidth: 50,
    },
    {
      type: "select",
      label: "物流信息",
      prop: "logisticsCompanyCode",
      itemWidth: 50,
      style: {
        width: "100%",
      },
    },
    {
      type: "input",
      label: " ",
      prop: "code",
      placeholder: "物流/快递单号",
      itemWidth: 50,
    },
    {
      type: "title",
      title: "发货明细",
    },
    {
      type: "slot",
      slotName: "detailSlot",
      label: "",
    },
  ],
  [
    {
      type: "title",
      title: "基础信息",
    },
    {
      type: "input",
      prop: "supplyName",
      label: "供应商",
      disabled: true,
      itemWidth: 50,
    },
    {
      type: "input",
      prop: "purchaseCode",
      label: "采购单号",
      disabled: true,
      itemWidth: 50,
    },
    {
      type: "select",
      label: "物流/快递单号",
      prop: "deliverGoodsId",
      itemWidth: 50,
      style: {
        width: "100%",
      },
    },
    {
      type: "title",
      title: "发货明细",
    },
    {
      type: "slot",
      slotName: "detailSlot",
      label: "",
    },
  ],
];

const deliverData = ref([]);
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/purchase/pageByWdly", sourceList.value.pagination)
    .then((message) => {
      console.log(message);
      sourceList.value.data = message.rows.map((x) => ({
        ...x,
        ...JSON.parse(x.victoriatouristJson),
      }));
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};

const submitForm = () => {
  byform.value.handleSubmit((valid) => {
    if (modalType.value === "add") {
      const list = formData.data.deliverGoodsDetailsList;
      const total = list.reduce(
        (total, x) => (total += Number(x.deliverGoodsQuantity)),
        0
      );
      if (!(total > 0)) {
        return ElMessage({
          message: `本次发货不能为0!`,
          type: "info",
        });
      }
      for (let i = 0; i < list.length; i++) {
        const e = list[i];
        if (
          Number(e.alreadyDeliverGoodsQuantity) +
            Number(e.deliverGoodsQuantity) >
          Number(e.count)
        ) {
          return ElMessage({
            message: `本次发货加累计发货不可大于采购数量!`,
            type: "info",
          });
        }
      }
      loading.value = true;
      formData.data.deliverGoodsDetailsList = list.map((x) => ({
        purchaseDetailId: x.purchaseDetailId,
        deliverGoodsQuantity: x.deliverGoodsQuantity,
      }));
      proxy.post("/deliverGoods/add", formData.data).then((res) => {
        ElMessage({
          message: `操作成功!`,
          type: "success",
        });
        dialogVisible.value = false;
        loading.value = false;
        getList();
      });
    } else if (modalType.value === "edit") {
      loading.value = true;
      formData.data.arrivalDetailList = formData.data.arrivalDetailList.map(
        (x) => ({
          bussinessId: x.bussinessId,
          purchaseDetailId: x.purchaseDetailId,
          deliverGoodsDetailsId: x.deliverGoodsDetailsId,
          count: x.deliverGoodsQuantity,
        })
      );
      const victoriatouristJson = {
        deliverGoodsId: formData.data.deliverGoodsId,
        logisticsCompanyCode: formData.data.logisticsCompanyCode,
        code: formData.data.code,
      };
      formData.data.victoriatouristJson = JSON.stringify(victoriatouristJson);
      proxy.post("/arrival/addByWdly", formData.data).then((res) => {
        ElMessage({
          message: `操作成功!`,
          type: "success",
        });
        dialogVisible.value = false;
        loading.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 supplierData = ref([]);
const getSupplierList = async (req) => {
  proxy
    .post("/supplierInfo/page", { pageNum: 1, pageSize: 9999 })
    .then((res) => {
      supplierData.value = res.rows;
    });
};

const logisticsData = ref([]);
const getLogisticsData = (row) => {
  proxy.post("/companyInfo/list", { pageNum: 1, pageSize: 999 }).then((res) => {
    logisticsData.value = res.reverse().slice(0, 100); //截取前100
  });
};

const handleArrival = (row, type) => {
  modalType.value = type;
  if (type === "add") {
    formConfig = configData[0];
    formConfig[3].data = logisticsData.value.map((x) => ({
      label: x.name,
      value: x.code,
    }));
    proxy.post("/deliverGoodsDetails/detail", { id: row.id }).then((res) => {
      formData.data = {
        purchaseId: row.id,
        supplyName: row.supplyName,
        purchaseCode: row.code,
        supplyId: res.supplyId,
        code: "",
        logisticsCompanyCode: "",
        deliverGoodsDetailsList: res.map((x) => ({
          ...x,
          purchaseDetailId: x.id,
          alreadyDeliverGoodsQuantity: x.deliverGoodsQuantity,
          deliverGoodsQuantity: 0,
        })),
      };
      dialogVisible.value = true;
    });
  } else if (type === "edit") {
    formConfig = configData[1];
    proxy.post("/deliverGoods/list", { id: row.id }).then((res) => {
      deliverData.value = res;
      formConfig[3].data = res.map((x) => ({
        ...x,
        label: x.code,
        value: x.id,
      }));
      formData.data = {
        purchaseId: row.id,
        supplyName: row.supplyName,
        purchaseCode: row.code,
        supplyId: row.supplyId,
        code: "",
        logisticsCompanyCode: "",
        deliverGoodsId: "",
        arrivalDetailList: [],
      };
      dialogVisible.value = true;
    });
  }
};

watch(
  () => formData.data.deliverGoodsId,
  (val) => {
    if (val) {
      const current = deliverData.value.find((x) => x.id === val);
      formData.data.logisticsCompanyCode = current
        ? current.logisticsCompanyCode
        : "";
      formData.data.code = current ? current.code : "";
      // formData.data.logisticsCompanyName = current ? current.logisticsCompanyCode : "";
      proxy.post("/deliverGoods/detail", { id: val }).then((res) => {
        formData.data.arrivalDetailList = res.map((x) => ({
          count: x.count,
          productName: x.name,
          productSpec: x.spec,
          productUnit: x.unit,
          productType: x.type,
          productCode: x.code,
          bussinessId: x.productId,
          purchaseDetailId: x.purchaseDetailId,
          deliverGoodsDetailsId: x.deliverGoodsId,
          transitQuantity: x.transitQuantity,
          deliverGoodsQuantity: x.deliverGoodsQuantity,
          productDefinition: x.definition,
        }));
      });
    }
  }
);

getList();
getLogisticsData();
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>