<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="[
          {
            text: '添加退货',
            action: () => start(),
          },
        ]"
        @get-list="getList"
      >
        <template #fileSlot="{ item }">
          <div
            style="cursor: pointer; color: #409eff"
            @click="handleClickFile(item)"
          >
            {{ item.fileName }}
          </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="单位" />
            <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="4"
                    :controls="false"
                    :min="0"
                    @change="handleChangeAmount"
                     onmousewheel="return false;"
                  />
                </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>
  </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,
  },
});
let dialogVisible = ref(false);
let modalType = ref("add");
let rules = ref({
  count: [{ required: true, message: "请输入本次到货", trigger: "blur" }],
});
const { proxy } = getCurrentInstance();
const selectConfig = reactive([
  {
    label: "退货状态",
    prop: "status",
    data: [
      {
        label: "审批中",
        value: "10",
      },
      {
        label: "驳回",
        value: "20",
      },
      {
        label: "待退货",
        value: "30",
      },
    ],
  },
  {
    label: "到货状态",
    prop: "arrivalStatus",
    data: [
      {
        label: "未到货",
        value: "0",
      },
      {
        label: "部分到货",
        value: "10",
      },
      {
        label: "已到货",
        value: "20",
      },
    ],
  },
  {
    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: "remarks",
      },
    },
    {
      attrs: {
        label: "物品名称",
        prop: "purchaseName",
      },
    },
    {
      attrs: {
        label: "单位",
        prop: "createTime",
      },
    },
    {
      attrs: {
        label: "退货数量",
        prop: "purchaseStatus",
      },
    },
    {
      attrs: {
        label: "退货状态",
        prop: "arrivalStatus",
      },
    },
    {
      attrs: {
        label: "退款状态",
        prop: "payStatus",
      },
    },
    {
      attrs: {
        label: "操作人",
        prop: "payStatus",
      },
    },
    {
      attrs: {
        label: "操作时间",
        prop: "payStatus",
      },
    },

    {
      attrs: {
        label: "操作",
        width: "100",
        align: "right",
      },
      renderHTML(row) {
        return [
          {
            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("/salesReturnDetail/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)));
      if (total < 1) {
        return ElMessage({
          message: `本次到货不能为0！`,
          type: "info",
        });
      }
      let sum = 0;
      for (let i = 0; i < list.length; i++) {
        const e = list[i];
        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 = true;
        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 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) => ({
        ...x,
        purchaseDetailId: x.id,
        purchaseCount: x.count,
        count: 0,
      })),
      arrivalStatus: "",
    };
    dialogVisible.value = true;
  });
};

getList();
getSupplierList();
const start = () => {
  proxy.$router.replace({
    path: "/platform_manage/process/processApproval",
    query: {
      isSubscribe: "40",
      ids: "",
    },
  });
};
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>