<template>
  <el-card class="box-card">
    <byTable
      :source="sourceList.data"
      :pagination="sourceList.pagination"
      :config="config"
      :loading="loading"
      :searchConfig="searchConfig"
      highlight-current-row
      :action-list="[
        {
          text: '同步万里牛售后单',
          action: () => clickSynchronousOrder(),
          loading: btnLoading,
        },
      ]"
      @get-list="getList"
      @clickReset="clickReset"
      :spanMethod="spanMethod"
      :borderStatus="true">
    </byTable>

    <el-dialog title="质检" v-if="openQualityTesting" v-model="openQualityTesting" width="500px">
      <el-form :model="rowData" ref="submit" :rules="rules" v-loading="loadingQualityTesting">
        <div style="margin: 10px 0; font-weight: 700; font-size: 18px; color: black">请根据质检结果选择，此裸垫是否可二次销售</div>
        <template v-if="rowData.orderExchangeDetailList && rowData.orderExchangeDetailList.length > 0">
          <div v-for="(item, index) in rowData.orderExchangeDetailList" :key="index" style="margin-top: 20px">
            <div style="margin-bottom: 10px">SKU品号：{{ item.skuSpecCode }}</div>
            <el-form-item
              label="质检通过数量"
              :prop="'orderExchangeDetailList.' + index + '.checkPassesQuantity'"
              :rules="rules.checkPassesQuantity"
              :inline-message="true">
              <el-input-number
                onmousewheel="return false;"
                v-model="item.checkPassesQuantity"
                placeholder="数量"
                style="width: 100%"
                :controls="false"
                :min="0"
                :precision="0" />
            </el-form-item>
          </div>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="openQualityTesting = false" size="large" v-preReClick>取 消</el-button>
        <el-button type="primary" @click="clickSubmit()" size="large" v-preReClick>质检完成</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import byTable from "/src/components/byTable/index";
import { ElMessage } from "element-plus";

const { proxy } = getCurrentInstance();
const departmentList = ref([]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    code: "",
    orderCode: "",
    orderWlnCode: "",
    departmentId: "",
    status: 0,
  },
});
const loading = ref(false);
const status = ref([
  {
    dictKey: 0,
    dictValue: "待质检",
  },
  {
    dictKey: 1,
    dictValue: "已质检入库",
  },
]);
const searchConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "code",
      label: "售后单号",
    },
    {
      type: "input",
      prop: "orderCode",
      label: "订单号",
    },
    {
      type: "input",
      prop: "orderWlnCode",
      label: "E10单号",
    },
    {
      type: "select",
      prop: "departmentId",
      data: departmentList.value,
      label: "事业部",
    },
    {
      type: "select",
      prop: "status",
      data: status.value,
      label: "质检状态",
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "售后库单号",
        prop: "code",
      },
    },
    {
      attrs: {
        label: "售后订单",
        prop: "orderCode",
      },
    },
    {
      attrs: {
        label: "E10单号",
        prop: "orderWlnCode",
      },
    },
    {
      attrs: {
        label: "退货事业部",
        prop: "departmentName",
      },
    },
    {
      attrs: {
        label: "SKU品号",
        prop: "skuSpecCode",
      },
    },
    {
      attrs: {
        label: "数量",
        prop: "quantity",
        width: 100,
      },
    },
    {
      attrs: {
        label: "退货金额",
        prop: "returnAmount",
        width: 120,
      },
    },
    {
      attrs: {
        label: "售后时间",
        prop: "createTime",
        align: "center",
        width: 160,
      },
    },
    {
      attrs: {
        label: "质检状态",
        prop: "status",
        width: 120,
      },
      render(val) {
        return proxy.dictKeyValue(val, status.value);
      },
    },
    {
      attrs: {
        label: "操作人",
        prop: "createUserName",
      },
    },
    {
      attrs: {
        label: "操作",
        width: 140,
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          row.status === 0
            ? {
                attrs: {
                  label: "质检",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  clickQualityTesting(row);
                },
              }
            : {},
          {
            attrs: {
              label: "查看详情",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              clickDetail(row);
            },
          },
        ];
      },
    },
  ];
});
const getDemandData = () => {
  proxy.post("/department/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      departmentList.value = res.rows.map((item) => {
        return {
          dictKey: item.id,
          dictValue: item.name,
        };
      });
    }
  });
};
getDemandData();
const mergeRow = (list) => {
  for (let field in list[0]) {
    let k = 0;
    let i = 0;
    while (k < list.length) {
      list[k][field + "Span"] = 1;
      list[k][field + "Dis"] = false;
      for (i = k + 1; i <= list.length - 1; i++) {
        if (list[k][field] === list[i][field] && list[k].id === list[i].id) {
          list[k][field + "Span"]++;
          list[k][field + "Dis"] = false;
          list[i][field + "Span"] = 1;
          list[i][field + "Dis"] = true;
        } else {
          break;
        }
      }
      k = i;
    }
  }
  return list;
};
const getList = async (req, status) => {
  if (status) {
    sourceList.value.pagination = {
      pageNum: sourceList.value.pagination.pageNum,
      pageSize: sourceList.value.pagination.pageSize,
    };
  } else {
    sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  }
  loading.value = true;
  proxy.post("/orderExchange/page", sourceList.value.pagination).then((res) => {
    let list = [];
    for (let i = 0; i < res.rows.length; i++) {
      if (res.rows[i].orderExchangeDetailList && res.rows[i].orderExchangeDetailList.length > 0) {
        for (let j = 0; j < res.rows[i].orderExchangeDetailList.length; j++) {
          list.push({
            id: res.rows[i].id,
            code: res.rows[i].code,
            orderCode: res.rows[i].orderCode,
            orderWlnCode: res.rows[i].orderWlnCode,
            departmentName: res.rows[i].departmentName,
            skuSpecCode: res.rows[i].orderExchangeDetailList[j].skuSpecCode,
            quantity: res.rows[i].orderExchangeDetailList[j].quantity,
            returnAmount: res.rows[i].orderExchangeDetailList[j].returnAmount,
            createTime: res.rows[i].createTime,
            createUserName: res.rows[i].createUserName,
            status: res.rows[i].status,
            orderExchangeDetailList: res.rows[i].orderExchangeDetailList,
          });
        }
      }
    }
    sourceList.value.data = Object.freeze(mergeRow(list));
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getList();
const clickReset = () => {
  getList("", true);
};
const clickDetail = (row) => {
  proxy.$router.replace({
    path: "/order/after-sale/initiate",
    query: {
      id: row.id,
      random: proxy.random(),
    },
  });
};
const spanMethod = ({ rowIndex, columnIndex }) => {
  if ([0, 1, 2, 3, 7, 8, 9].includes(columnIndex)) {
    let spanName = ["code", "orderCode", "orderWlnCode", "departmentName", "", "", "", "createTime", "createUserName", "id"];
    const row1 = sourceList.value.data[rowIndex][spanName[columnIndex] + "Span"];
    const colspan = sourceList.value.data[rowIndex][spanName[columnIndex] + "Dis"] ? 0 : 1;
    const rowspan = colspan === 1 ? row1 : 0;
    return {
      rowspan: rowspan,
      colspan: colspan,
    };
  }
};
const rowData = ref({});
const openQualityTesting = ref(false);
const loadingQualityTesting = ref(false);
const rules = ref({
  checkPassesQuantity: [{ required: true, message: "请输入质检通过数量", trigger: "blur" }],
});
const clickQualityTesting = (item) => {
  rowData.value = proxy.deepClone(item);
  if (rowData.value.orderExchangeDetailList && rowData.value.orderExchangeDetailList.length > 0) {
    rowData.value.orderExchangeDetailList = rowData.value.orderExchangeDetailList.map((row) => {
      return {
        ...row,
        checkPassesQuantity: row.quantity,
      };
    });
  }
  loadingQualityTesting.value = false;
  openQualityTesting.value = true;
};
const clickSubmit = () => {
  proxy.$refs.submit.validate((valid) => {
    if (valid) {
      loadingQualityTesting.value = true;
      proxy.post("/orderExchange/orderExchangeCheck", rowData.value).then(
        () => {
          ElMessage({ message: "质检完成", type: "success" });
          openQualityTesting.value = false;
          getList();
        },
        (err) => {
          console.log(err);
          loadingQualityTesting.value = false;
        }
      );
    }
  });
};
const btnLoading = ref(false);
const clickSynchronousOrder = () => {
  btnLoading.value = true;
  proxy.post("/orderHandle/resynchronizationReturnOrder", {}).then(
    () => {
      ElMessage.success("同步完成成功");
      btnLoading.value = false;
      getList();
    },
    (err) => {
      ElMessage.error(`同步失败: ${err} ！`);
      btnLoading.value = false;
    }
  );
};
</script>

<style lang="scss" scoped>
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
