<template>
  <el-card class="box-card">
    <byTable
      :source="sourceList.data"
      :pagination="sourceList.pagination"
      :config="config"
      :loading="loading"
      :searchConfig="searchConfig"
      highlight-current-row
      :action-list="[
        judgeRoles()
          ? {
              text: '新建订单',
              action: () => clickAddOrder(),
            }
          : {},
      ]"
      @get-list="getList"
      @clickReset="clickReset">
      <template #code="{ item }">
        <div>
          <a style="color: #409eff; cursor: pointer; word-break: break-all" @click="clickCode(item)">{{ item.code }}</a>
        </div>
      </template>
      <template #totalAmount="{ item }">
        <div style="color: #409eff">{{ moneyFormat(item.totalAmount) }}</div>
      </template>
      <template #address="{ item }">
        <div>{{ item.province }}, {{ item.city }}, {{ item.county }}, {{ item.detailedAddress }}</div>
      </template>
    </byTable>

    <el-dialog title="订单删除申请" v-if="openApplyForCancellation" v-model="openApplyForCancellation" width="600" style="margin-top: 20vh !important">
      <el-form :model="formData.data" label-width="120px" :rules="rules" ref="submit">
        <el-form-item label="订单删除原因:" prop="remark">
          <el-input v-model="formData.data.remark" :rows="4" type="textarea" placeholder="请输入订单删除原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="openApplyForCancellation = false" size="large">取 消</el-button>
        <el-button type="primary" @click="clickSubmit()" size="large" v-preReClick>确 认</el-button>
      </template>
    </el-dialog>

    <el-dialog title="下一处理人" v-if="openSelectUser" v-model="openSelectUser" width="500" style="margin-top: 20vh !important">
      <el-form :model="formData.data" label-width="100px" :rules="rules" ref="submitUser">
        <el-form-item label="处理人:" prop="handleUserId">
          <el-select v-model="formData.data.handleUserId" placeholder="请选择处理人" filterable style="width: 100%">
            <el-option v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="openSelectUser = false" size="large">取 消</el-button>
        <el-button type="primary" @click="clickSubmitUser()" size="large" v-preReClick>确 认</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import byTable from "/src/components/byTable/index";
import { ElMessage, ElMessageBox } from "element-plus";
import refreshStore from "/src/store/modules/refresh";

const { proxy } = getCurrentInstance();
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    departmentId: proxy.useUserStore().user.deptId === "100" ? "" : proxy.useUserStore().user.deptId,
    code: "",
    wlnCode: "",
    status: "",
    settlementStatus: "",
    exception: "0",
  },
});
const loading = ref(false);
const searchConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "code",
      label: "订单号",
    },
    {
      type: "input",
      prop: "wlnCode",
      label: "E10单号",
    },
    {
      type: "select",
      prop: "status",
      dictKey: "order_status",
      label: "订单状态",
    },
    {
      type: "select",
      prop: "settlementStatus",
      label: "结算状态",
      data: proxy.useUserStore().allDict["settlement_status"],
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "事业部",
        prop: "departmentName",
        width: 120,
      },
    },
    {
      attrs: {
        label: "订单号",
        slot: "code",
        width: 200,
      },
    },
    {
      attrs: {
        label: "E10单号",
        prop: "wlnCode",
        width: 160,
      },
    },
    {
      attrs: {
        label: "快递单号",
        prop: "expressDeliveryCode",
        width: 140,
      },
    },
    {
      attrs: {
        label: "订单状态",
        prop: "status",
        width: 120,
      },
      render(val) {
        return proxy.dictKeyValue(val, proxy.useUserStore().allDict["order_status"]);
      },
    },
    {
      attrs: {
        label: "结算状态",
        prop: "settlementStatus",
        width: 120,
      },
      render(val) {
        return proxy.dictKeyValue(val, proxy.useUserStore().allDict["settlement_status"]);
      },
    },
    {
      attrs: {
        label: "税率",
        prop: "taxRate",
        width: 80,
      },
      render(val) {
        return val + "%";
      },
    },
    {
      attrs: {
        label: "订单总金额 ¥",
        slot: "totalAmount",
        width: 120,
        align: "right",
      },
    },
    {
      attrs: {
        label: "产品总金额 ¥",
        prop: "productTotalAmount",
        width: 120,
        align: "right",
      },
      render(val) {
        return proxy.moneyFormat(val);
      },
    },
    {
      attrs: {
        label: "定制加工费 ¥",
        prop: "customProcessingFee",
        width: 120,
        align: "right",
      },
      render(val) {
        return proxy.moneyFormat(val);
      },
    },
    {
      attrs: {
        label: "代发费 ¥",
        prop: "lssueFee",
        width: 120,
        align: "right",
      },
      render(val) {
        return proxy.moneyFormat(val);
      },
    },
    {
      attrs: {
        label: "快递包材费 ¥",
        prop: "deliveryMaterialsFee",
        width: 120,
        align: "right",
      },
      render(val) {
        return proxy.moneyFormat(val);
      },
    },
    {
      attrs: {
        label: "包装人工费 ¥",
        prop: "packingLabor",
        width: 120,
        align: "right",
      },
      render(val) {
        return proxy.moneyFormat(val);
      },
    },
    {
      attrs: {
        label: "包材费 ¥",
        prop: "packagingMaterialCost",
        width: 120,
        align: "right",
      },
      render(val) {
        return proxy.moneyFormat(val);
      },
    },
    {
      attrs: {
        label: "管理费 ¥",
        prop: "managementFee",
        width: 120,
        align: "right",
      },
      render(val) {
        return proxy.moneyFormat(val);
      },
    },
    {
      attrs: {
        label: "交期",
        prop: "deliveryTime",
        width: 160,
        align: "center",
      },
    },
    {
      attrs: {
        label: "发货时间",
        prop: "shippingTime",
        width: 160,
        align: "center",
      },
    },
    {
      attrs: {
        label: "收货人",
        prop: "consignee",
        width: 140,
      },
    },
    {
      attrs: {
        label: "收货人电话",
        prop: "consigneeNumber",
        width: 140,
      },
    },
    {
      attrs: {
        label: "收货人地址",
        slot: "address",
        width: 400,
      },
    },
    {
      attrs: {
        label: "操作",
        width: 160,
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          row.status == 10 && ![14].includes(row.wlnStatus)
            ? {
                attrs: {
                  label: "上传设计稿",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  clickUpload(row);
                },
              }
            : {},
          row.status == 0
            ? {
                attrs: {
                  label: "编辑",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  clickUpdate(row);
                },
              }
            : {},
          row.status == 10
            ? {
                attrs: {
                  label: "删除",
                  type: "danger",
                  text: true,
                },
                el: "button",
                click() {
                  clickDelete(row);
                },
              }
            : {},
          row.status == 30
            ? {
                attrs: {
                  label: "申请订单取消",
                  type: "danger",
                  text: true,
                },
                el: "button",
                click() {
                  clickApplyForCancellation(row);
                },
              }
            : {},
        ];
      },
    },
  ];
});
const getList = async (req, status) => {
  if (status) {
    sourceList.value.pagination = {
      pageNum: sourceList.value.pagination.pageNum,
      pageSize: sourceList.value.pagination.pageSize,
      departmentId: proxy.useUserStore().user.deptId === "100" ? "" : proxy.useUserStore().user.deptId,
      exception: "0",
    };
  } else {
    sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  }
  loading.value = true;
  proxy.post("/orderInfo/page", sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getList();
const clickReset = () => {
  getList("", true);
};
const clickAddOrder = () => {
  proxy.$router.replace({
    path: "/addOrder",
    query: {
      random: proxy.random(),
    },
  });
};
const clickCode = (row) => {
  proxy.$router.replace({
    path: "/addOrder",
    query: {
      detailId: row.id,
      text: "订单详情",
      random: proxy.random(),
    },
  });
};
const clickDelete = (row) => {
  ElMessageBox.confirm("你是否确认此操作", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      proxy.post("/orderInfo/delete", { id: row.id }).then(() => {
        ElMessage({ message: "删除成功", type: "success" });
        getList();
      });
    })
    .catch(() => {});
};
const clickUpdate = (row) => {
  proxy.$router.replace({
    path: "/addOrder",
    query: {
      id: row.id,
      text: "编辑订单",
      random: proxy.random(),
    },
  });
};
const clickUpload = (row) => {
  proxy.$router.replace({
    path: "/design-draft",
    query: {
      id: row.id,
      random: proxy.random(),
    },
  });
};
watch(refreshStore().refresh, (val) => {
  if (val.order) {
    getList();
  }
});
const judgeRoles = () => {
  let status = false;
  if (proxy.useUserStore().user.roles && proxy.useUserStore().user.roles.length > 0) {
    let list = proxy.useUserStore().user.roles.filter((item) => ["purchasingOfficer", "sypurchasing", "bzpurchasing"].includes(item.roleKey));
    if (list && list.length > 0) {
      status = true;
    }
  }
  return status;
};
const openApplyForCancellation = ref(false);
const formData = reactive({
  data: {
    flowKey: "order_delete",
    remark: "",
    handleUserId: "",
    data: {
      id: "",
    },
  },
});
const rules = ref({
  remark: [{ required: true, message: "请输入订单删除原因", trigger: "blur" }],
  handleUserId: [{ required: true, message: "请选择处理人", trigger: "change" }],
});
const clickApplyForCancellation = (row) => {
  formData.data.remark = "";
  formData.data.handleUserId = "";
  formData.data.data.id = row.id;
  openApplyForCancellation.value = true;
};
const userList = ref([]);
const openSelectUser = ref(false);
const clickSubmit = () => {
  proxy.$refs.submit.validate((valid) => {
    if (valid) {
      proxy.post("/flowProcess/initiate", formData.data).then((res) => {
        if (res !== null && res.success) {
          ElMessage({ message: "提交成功", type: "success" });
          openApplyForCancellation.value = false;
        } else {
          userList.value = res.userList;
          openSelectUser.value = true;
        }
      });
    }
  });
};
const clickSubmitUser = () => {
  proxy.$refs.submitUser.validate((valid) => {
    if (valid) {
      proxy.post("/flowProcess/initiate", formData.data).then((res) => {
        if (res !== null && res.success) {
          ElMessage({ message: "提交成功", type: "success" });
          openApplyForCancellation.value = false;
          openSelectUser.value = false;
        } else {
          ElMessage("流程提交失败");
        }
      });
    }
  });
};
</script>

<style lang="scss" scoped>
:deep(.el-dialog) {
  margin-top: 10px !important;
  margin-bottom: 10px !important;
}
</style>
