<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: 'Excel导入',
            action: () => openExcel(),
            disabled: false,
          },
        ]"
        @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"
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="byform"
      >
        <template #detailSlot>
          <div style="width: 100%">
            <el-button
              type="primary"
              @click="openProduct = true"
              style="margin-bottom: 10px"
              v-if="modalType != 'detail'"
            >
              添加物品
            </el-button>
            <el-table :data="formData.data.jdBackDetailsList">
              <el-table-column prop="productCode" label="货品编码" />
              <el-table-column prop="productName" label="货品名称" />
              <el-table-column prop="quantity" label="退货数量" min-width="150">
                <template #default="{ row, $index }">
                  <el-form-item
                    :prop="'jdBackDetailsList.' + $index + '.quantity'"
                    :rules="rules.quantity"
                    :inline-message="true"
                  >
                    <el-input-number
                      v-model="row.quantity"
                      :precision="4"
                      :controls="false"
                      :min="0"
                      onmousewheel="return false;"
                    />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="zip"
                label="操作"
                width="100"
                v-if="modalType != 'detail'"
              >
                <template #default="{ $index }">
                  <el-button type="primary" link @click="handleRemove($index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </byForm>

      <template #footer v-if="modalType != 'detail'">
        <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
      v-model="openProduct"
      title="选择产品"
      width="70%"
      append-to-body
    >
      <SelectProduct @handleSelect="handleSelect"></SelectProduct>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="openProduct = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      title="Excel导入"
      v-model="openExcelDialog"
      width="400"
      v-loading="excelLoading"
    >
      <div style="margin-bottom: 10px">导入前请先选择仓库</div>
      <el-select v-model="importData.warehouseId" placeholder="请选择仓库">
        <el-option
          v-for="item in warehouseList"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <div style="margin-top: 20px" v-show="importData.warehouseId">
        <el-upload
          :action="actionUrl + '/salesRecord/excelImport'"
          :data="importData"
          :headers="headers"
          :on-success="handleSuccess"
          :on-progress="handleProgress"
          :show-file-list="false"
          :on-error="handleError"
          accept=".xlsx"
        >
          <el-button type="primary">点击导入</el-button>
        </el-upload>
      </div>

      <template #footer>
        <el-button @click="openExcelDialog = false" size="large"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="submitExcel()"
          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";
import SelectProduct from "@/components/WDLY/product/SelectProduct";
import { getToken } from "@/utils/auth";

const uploadData = ref({});
const headers = ref({ Authorization: "Bearer " + getToken() });
const actionUrl = import.meta.env.VITE_APP_BASE_API;

const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
  },
});
let dialogVisible = ref(false);
let openProduct = ref(false);
let openExcelDialog = ref(false);
let excelLoading = ref(false);

let modalType = ref("add");
let rules = ref({
  warehouseId: [{ required: true, message: "请选择仓库", trigger: "change" }],
  logisticsCompanyCode: [
    { required: true, message: "请选择物流公司", trigger: "change" },
  ],
  logisticsCode: [
    { required: true, message: "请输入物流/快递单号", trigger: "blur" },
  ],
  quantity: [{ required: true, message: "请输入退货数量", trigger: "blur" }],
});
const { proxy } = getCurrentInstance();
const selectConfig = reactive([]);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "销售日期",
        prop: "dateSale",
      },
    },

    {
      attrs: {
        label: "产品分类",
        prop: "warehouseName",
      },
    },
    {
      attrs: {
        label: "产品编码",
        prop: "warehouseName",
      },
    },
    {
      attrs: {
        label: "产品名称",
        prop: "logisticsCompanyName",
      },
    },
    {
      attrs: {
        label: "规格型号",
        prop: "logisticsCode",
      },
    },
    {
      attrs: {
        label: "单位",
        prop: "createTime",
      },
    },
    {
      attrs: {
        label: "销售数量",
        prop: "quantity",
      },
    },
    {
      attrs: {
        label: "导入时间",
        prop: "createTime",
      },
    },
  ];
});

let formData = reactive({
  data: {},
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
});
const byform = ref(null);
let formConfig = reactive([
  {
    type: "title",
    title: "退货信息",
  },
  {
    type: "select",
    prop: "warehouseId",
    label: "仓库名称",
    itemWidth: 100,
    disabled: false,
    data: [],
  },
  {
    type: "select",
    label: "物流信息",
    prop: "logisticsCompanyCode",
    filterable: true,
    data: [],
    itemWidth: 50,
    style: {
      width: "100%",
    },
  },
  {
    type: "input",
    label: " ",
    prop: "logisticsCode",
    itemWidth: 50,
  },
  {
    type: "slot",
    slotName: "detailSlot",
    label: "发货明细",
  },
]);
const configData = [
  [
    {
      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",
      itemWidth: 50,
    },
    {
      type: "slot",
      slotName: "detailSlot",
      label: "发货明细",
    },
  ],
  [
    {
      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: "slot",
      slotName: "detailSlot",
      label: "发货明细",
    },
  ],
];

const deliverData = ref([]);
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/salesRecord/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 = () => {
  byform.value.handleSubmit((valid) => {
    const list = formData.data.jdBackDetailsList;
    if (!list.length > 0) {
      return ElMessage({
        message: `请添加退货明细`,
        type: "info",
      });
    }
    for (let i = 0; i < list.length; i++) {
      const e = list[i];
      if (e.quantity == 0) {
        return ElMessage({
          message: `退货数量不能为0！`,
          type: "info",
        });
      }
    }
    loading.value = true;
    submitLoading.value = true;
    proxy.post("/jdBack/" + modalType.value, formData.data).then(
      (res) => {
        ElMessage({
          message: `操作成功！`,
          type: "success",
        });
        dialogVisible.value = false;
        submitLoading.value = false;
        loading.value = false;
        getList();
      },
      (err) => (submitLoading.value = false)
    );
  });
};

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

const importData = reactive({});

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 logisticsData = ref([]);
const getLogisticsData = (row) => {
  proxy.post("/companyInfo/list", { pageNum: 1, pageSize: 999 }).then((res) => {
    // logisticsData.value = res.reverse().slice(0, 100); //截取前100
    logisticsData.value = res.reverse();
    formConfig[2].data = logisticsData.value.map((x) => ({
      label: x.name,
      value: x.code,
    }));
  });
};

watch(modalType, (val) => {
  if (val) {
    formConfig[1].disabled = val == "detail" ? true : false;
    formConfig[2].disabled = val == "detail" ? true : false;
    formConfig[3].disabled = val == "detail" ? true : false;
  }
});
const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formData.data = {
    type: "1",
    status: "1",
    jdBackDetailsList: [],
  };
};

const warehouseList = ref([]);
const warehouseListData = () => {
  // // 币种数据
  proxy
    .post("/warehouse/page", {
      pageNum: 1,
      pageSize: 10,
    })
    .then((message) => {
      warehouseList.value = message.rows;
      formConfig[1].data = message.rows.map((x) => ({
        label: x.name,
        value: x.id,
      }));
    });
};

getList();
getLogisticsData();
warehouseListData();

const handleSelect = (row) => {
  const flag = formData.data.jdBackDetailsList.some(
    (x) => x.productId === row.id
  );
  if (flag)
    return ElMessage({
      message: "该物品已选择",
      type: "info",
    });
  formData.data.jdBackDetailsList.push({
    quantity: null,
    productName: row.name,
    productCode: row.code,
    productId: row.id,
  });
  return ElMessage({
    message: "选择成功",
    type: "success",
  });
};

const handleRemove = (index) => {
  formData.data.jdBackDetailsList.splice(index, 1);
  return ElMessage({
    message: "删除成功",
    type: "success",
  });
};
const openExcel = () => {
  openExcelDialog.value = true;
};

const handleProgress = () => {
  excelLoading.value = true;
};
const handleError = (err) => {
  ElMessage({
    message: `${err}，请重试！`,
    type: "info",
  });
  openExcelDialog.value = false;
  excelLoading.value = false;
};
const handleSuccess = (res) => {
  if (res.code != 200) {
    return ElMessage({
      message: `${res.msg}，请重试！`,
      type: "info",
    });
  } else {
    ElMessage({
      message: "导入成功！",
      type: "success",
    });
    openExcelDialog.value = false;
    excelLoading.value = false;
    getList();
  }
};
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>