<template>
  <el-card class="box-card">
    <byTable
      :source="sourceList.data"
      :pagination="sourceList.pagination"
      :config="config"
      :loading="loading"
      :searchConfig="searchConfig"
      highlight-current-row
      :defaultExpandAll="true"
      :table-events="{
        select: selectRow,
        'select-all': selectRow,
      }"
      :action-list="[
        {
          text: '拆分包裹',
          action: () => clickUnpack(),
        },
        {
          text: '合并订单',
          action: () => clickMerge(),
        },
        {
          text: '取消合并',
          action: () => clickUnMerge(),
        },
        {
          text: '修改收件信息',
          action: () => clickModifyInformation(),
        },
        {
          text: '修改快递',
          action: () => clickModifiedExpress(),
        },
        {
          text: '打印快递单',
          action: () => clickPrint(),
          type: 'warning',
        },
        {
          text: '填写线下快递单号',
          action: () => clickFillInExpressCode(),
        },
      ]"
      @get-list="getList"
      @clickReset="clickReset">
      <template #typeExpand="{ item }">
        <div class="remark" v-html="item.remark"></div>
      </template>
      <template #code="{ item }">
        <div>
          <a style="color: #409eff; cursor: pointer; word-break: break-all" @click="clickCode(item)">{{ item.code }}</a>
        </div>
      </template>
      <template #groupOrderCodeList="{ item }">
        <div>
          <div v-if="item.groupOrderCodeList && item.groupOrderCodeList.length > 0">{{ item.groupOrderCodeList.join(",") }}</div>
        </div>
      </template>
      <template #total="{ item }">
        <div>
          <a style="color: #409eff; cursor: pointer; word-break: break-all" @click="clickTotal(item)">{{ item.total }}</a>
        </div>
      </template>
      <template #address="{ item }">
        <div>{{ item.province }},{{ item.city }},{{ item.county }},{{ item.detailedAddress }}</div>
      </template>
    </byTable>

    <el-dialog title="包裹规格数据" v-if="openTotal" v-model="openTotal" width="90%">
      <PackTotal :rowData="rowData" @clickCancel="clickCancel"></PackTotal>
    </el-dialog>

    <el-dialog title="包裹图片" v-if="openPackagePicture" v-model="openPackagePicture" width="70%">
      <div v-loading="loadingPackagePicture">
        <el-upload
          v-model:file-list="fileList"
          action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
          list-type="picture-card"
          multiple
          :data="uploadData"
          :before-upload="beforeUpload"
          :on-preview="onPreview">
          <el-icon><Plus /></el-icon>
        </el-upload>
      </div>
      <template #footer>
        <el-button @click="openPackagePicture = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitPicture()" size="large" v-preReClick>提 交</el-button>
      </template>
    </el-dialog>

    <el-dialog title="合并订单" v-if="openMerge" v-model="openMerge" width="500">
      <el-form :model="formMerge.data" :rules="rulesMerge" label-width="100px" ref="refMerge">
        <el-form-item label="主订单号" prop="id">
          <el-select v-model="formMerge.data.id" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in selectData" :key="item.id" :label="item.code" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合并订单号" prop="mergeIdList">
          <el-select v-model="formMerge.data.mergeIdList" placeholder="请选择" style="width: 100%" multiple :disabled="!formMerge.data.id">
            <el-option v-for="item in selectData.filter((item) => item.id !== formMerge.data.id)" :key="item.id" :label="item.code" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="openMerge = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitMerge()" size="large" v-preReClick>提 交</el-button>
      </template>
    </el-dialog>

    <el-dialog title="修改收件信息" v-if="openInformation" v-model="openInformation" width="600">
      <el-form :model="formInformation.data" :rules="rulesInformation" label-width="120px" ref="refInformation">
        <el-form-item label="省" prop="province">
          <el-input v-model="formInformation.data.province" placeholder="请输入省" />
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-input v-model="formInformation.data.city" placeholder="请输入市" />
        </el-form-item>
        <el-form-item label="区/县" prop="county">
          <el-input v-model="formInformation.data.county" placeholder="请输入区/县" />
        </el-form-item>
        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input v-model="formInformation.data.detailedAddress" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="收货人" prop="consignee">
          <el-input v-model="formInformation.data.consignee" placeholder="请输入收货人" />
        </el-form-item>
        <el-form-item label="收货人电话" prop="consigneeNumber">
          <el-input v-model="formInformation.data.consigneeNumber" placeholder="请输入收货人电话" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="openInformation = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitInformation()" size="large" v-preReClick>保 存</el-button>
      </template>
    </el-dialog>

    <el-dialog title="修改快递" v-if="openExpress" v-model="openExpress" width="500">
      <el-form :model="formExpress.data" :rules="rulesExpress" label-width="100px" ref="refExpress">
        <el-form-item label="快递" prop="expressDeliveryId">
          <el-select v-model="formExpress.data.expressDeliveryId" placeholder="请选择快递" style="width: 100%">
            <el-option v-for="item in expressDeliveryList.value" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="openExpress = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitExpress()" size="large" v-preReClick>保 存</el-button>
      </template>
    </el-dialog>

    <el-dialog title="修改快递" v-if="openExpressCode" v-model="openExpressCode" width="500">
      <el-form :model="formExpressCode.data" :rules="rulesExpressCode" label-width="100px" ref="refExpressCode">
        <el-form-item label="快递单号" prop="expressDeliveryCode">
          <el-input v-model="formExpressCode.data.expressDeliveryCode" placeholder="请输入快递单号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="openExpressCode = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitExpressCode()" 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";
import PackTotal from "/src/views/production/shipment/print-order/packTotal.vue";

const { proxy } = getCurrentInstance();
const departmentList = ref([{ dictKey: "0", dictValue: "胜德体育" }]);
const expressDeliveryList = ref([]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    code: "",
    departmentId: "",
    expressDeliveryCode: "",
    printStatus: "",
    beginTime: "",
    endTime: "",
  },
});
const loading = ref(false);
const searchConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "code",
      label: "订单号",
    },
    {
      type: "select",
      prop: "departmentId",
      data: departmentList.value,
      label: "事业部",
    },
    {
      type: "input",
      prop: "expressDeliveryCode",
      label: "快递单号",
    },
    {
      type: "select",
      prop: "printStatus",
      data: [
        {
          dictKey: "1",
          dictValue: "是",
        },
        {
          dictKey: "0",
          dictValue: "否",
        },
      ],
      label: "打印状态",
    },
    {
      type: "date",
      propList: ["beginTime", "endTime"],
      label: "交期",
    },
  ];
});
const config = computed(() => {
  return [
    {
      type: "expand",
      attrs: {
        label: " ",
        slot: "typeExpand",
        width: 50,
      },
    },
    {
      type: "selection",
      attrs: {
        checkAtt: "isCheck",
      },
    },
    // {
    //   attrs: {
    //     label: "日期",
    //     slot: "backupDateStr",
    //     width: 220,
    //     align: "center",
    //   },
    // },
    {
      attrs: {
        label: "主订单号",
        slot: "code",
        width: 160,
      },
    },
    {
      attrs: {
        label: "合并订单号",
        slot: "groupOrderCodeList",
        width: 160,
      },
    },
    {
      attrs: {
        label: "总包裹数",
        slot: "total",
        width: 90,
      },
    },
    {
      attrs: {
        label: "事业部",
        prop: "departmentName",
        width: 130,
      },
    },
    {
      attrs: {
        label: "快递",
        prop: "expressDeliveryName",
        width: 130,
      },
    },
    {
      attrs: {
        label: "快递单号",
        prop: "expressDeliveryCode",
        width: 130,
      },
    },
    {
      attrs: {
        label: "店铺来源",
        prop: "sourcePlatform",
        width: 120,
      },
    },
    {
      attrs: {
        label: "店铺名称",
        prop: "shopName",
        width: 140,
      },
    },
    {
      attrs: {
        label: "下单时间",
        prop: "createTime",
        width: 160,
        align: "center",
      },
    },
    {
      attrs: {
        label: "交期",
        prop: "deliveryTime",
        width: 160,
        align: "center",
      },
    },
    {
      attrs: {
        label: "收货人",
        prop: "consignee",
        width: 120,
      },
    },
    {
      attrs: {
        label: "收货人电话",
        prop: "consigneeNumber",
        width: 160,
      },
    },
    {
      attrs: {
        label: "收货地址",
        slot: "address",
        width: 300,
      },
    },
    {
      attrs: {
        label: "总净重(kg)",
        prop: "totalNetWeight",
        width: 120,
        fixed: "right",
      },
    },
    {
      attrs: {
        label: "总体积(m³)",
        prop: "totalVolume",
        width: 120,
        fixed: "right",
      },
    },
    {
      attrs: {
        label: "操作",
        width: 100,
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "包裹图片",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              clickPackagePicture(row);
            },
          },
        ];
      },
    },
  ];
});
const getDemandData = () => {
  proxy.post("/department/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      departmentList.value = departmentList.value.concat(
        res.rows.map((item) => {
          return {
            dictKey: item.id,
            dictValue: item.name,
          };
        })
      );
    }
  });
  proxy.post("/expressDelivery/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      expressDeliveryList.value = res.rows.map((item) => {
        return {
          dictKey: item.id,
          dictValue: item.expressage,
        };
      });
    }
  });
};
getDemandData();
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("/issueBill/page", sourceList.value.pagination).then((res) => {
    if (res.rows && res.rows.length > 0) {
      sourceList.value.data = res.rows.map((item) => {
        return {
          ...item,
          isCheck: true,
        };
      });
    } else {
      sourceList.value.data = [];
    }
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getList();
const clickReset = () => {
  getList("", true);
};
const selectData = ref([]);
const selectRow = (data) => {
  selectData.value = data;
};
const clickCode = (row) => {
  proxy.$router.replace({
    path: "/order-detail",
    query: {
      detailId: row.id,
      text: "订单详情",
      random: proxy.random(),
    },
  });
};
const openTotal = ref(false);
const rowData = ref({});
const clickTotal = (item) => {
  rowData.value = item;
  openTotal.value = true;
};
const clickCancel = () => {
  openTotal.value = false;
};
const openPackagePicture = ref(false);
const loadingPackagePicture = ref(false);
const fileList = ref([]);
const clickPackagePicture = (item) => {
  fileList.value = [];
  rowData.value = item;
  openPackagePicture.value = true;
  loadingPackagePicture.value = true;
  proxy.post("/fileInfo/getList", { businessIdList: [item.id] }).then(
    (fileObj) => {
      if (fileObj[item.id] && fileObj[item.id].length > 0) {
        let file = fileObj[item.id].filter((item) => item.businessType == "2");
        if (file && file.length > 0) {
          fileList.value = file.map((item) => {
            return {
              raw: item,
              name: item.fileName,
              url: item.fileUrl,
            };
          });
        } else {
          fileList.value = [];
        }
      }
      loadingPackagePicture.value = false;
    },
    (err) => {
      console.log(err);
      loadingPackagePicture.value = false;
    }
  );
};
const uploadData = ref({});
const beforeUpload = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  file.id = res.id;
  file.fileName = res.fileName;
  file.fileUrl = res.fileUrl;
  return true;
};
const onPreview = (file) => {
  window.open(file.raw.fileUrl, "_blank");
};
const submitPicture = () => {
  let packagePictureList = [];
  if (fileList.value && fileList.value.length > 0) {
    packagePictureList = fileList.value.map((item) => {
      return {
        id: item.raw.id,
        fileName: item.raw.fileName,
        fileUrl: item.raw.fileUrl,
      };
    });
  }
  loadingPackagePicture.value = true;
  proxy.post("/issueBill/editPackagePicture", { id: rowData.value.id, packagePictureList: packagePictureList }).then(
    () => {
      openPackagePicture.value = false;
      loadingPackagePicture.value = false;
      ElMessage({ message: "提交成功", type: "success" });
    },
    (err) => {
      console.log(err);
      loadingPackagePicture.value = false;
    }
  );
};
const clickUnpack = () => {
  if (selectData.value && selectData.value.length > 0) {
    if (selectData.value.length > 1) {
      return ElMessage("每次只能选一个");
    }
    proxy.$router.replace({
      path: "/production/shipment/unpack",
      query: {
        id: selectData.value[0].id,
      },
    });
  } else {
    return ElMessage("请先选择需要拆分包裹的订单");
  }
};
const openMerge = ref(false);
const formMerge = reactive({
  data: {
    id: "",
    mergeIdList: [],
  },
});
const rulesMerge = ref({
  id: [{ required: true, message: "请选择主订单", trigger: "change" }],
  mergeIdList: [{ required: true, message: "请选择合并订单", trigger: "change" }],
});
const clickMerge = () => {
  if (selectData.value && selectData.value.length > 1) {
    for (let i = 0; i < selectData.value.length; i++) {
      if (selectData.value[i].groupOrderCodeList && selectData.value[i].groupOrderCodeList.length > 0) {
        return ElMessage("请选择未合并订单进行合并");
      }
    }
    formMerge.data = {
      id: "",
      mergeIdList: [],
    };
    openMerge.value = true;
  } else {
    return ElMessage("请选择需要合并的订单");
  }
};
const submitMerge = () => {
  proxy.$refs.refMerge.validate((valid) => {
    if (valid) {
      proxy.post("/issueBill/merge", formMerge.data).then(() => {
        openMerge.value = false;
        ElMessage({ message: "提交成功", type: "success" });
        getList();
      });
    }
  });
};
const clickUnMerge = () => {
  if (selectData.value && selectData.value.length > 0) {
    if (selectData.value.length > 1) {
      return ElMessage("每次只能选一个");
    }
    if (!(selectData.value[0].groupOrderCodeList && selectData.value[0].groupOrderCodeList.length > 0)) {
      return ElMessage("该订单没有合并");
    }
    proxy.post("/issueBill/unmerge", { id: selectData.value[0].id }).then(() => {
      ElMessage({ message: "取消合并成功", type: "success" });
      getList();
    });
  } else {
    return ElMessage("请先选择需要取消合并的订单");
  }
};
const openInformation = ref(false);
const formInformation = reactive({
  data: {
    id: "",
    province: "",
    city: "",
    county: "",
    detailedAddress: "",
    consignee: "",
    consigneeNumber: "",
  },
});
const rulesInformation = ref({
  province: [{ required: true, message: "请输入省", trigger: "blur" }],
  city: [{ required: true, message: "请输入市", trigger: "blur" }],
  county: [{ required: true, message: "请输入县", trigger: "blur" }],
  detailedAddress: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
  consignee: [{ required: true, message: "请输入收货人", trigger: "blur" }],
  consigneeNumber: [{ required: true, message: "请输入收货人电话", trigger: "blur" }],
});
const clickModifyInformation = () => {
  if (selectData.value && selectData.value.length > 0) {
    if (selectData.value.length > 1) {
      return ElMessage("每次只能选一个");
    }
    formInformation.data = {
      id: selectData.value[0].id,
      province: selectData.value[0].province,
      city: selectData.value[0].city,
      county: selectData.value[0].county,
      detailedAddress: selectData.value[0].detailedAddress,
      consignee: selectData.value[0].consignee,
      consigneeNumber: selectData.value[0].consigneeNumber,
    };
    openInformation.value = true;
  } else {
    return ElMessage("请先选择需要修改收件信息的订单");
  }
};
const submitInformation = () => {
  proxy.$refs.refInformation.validate((valid) => {
    if (valid) {
      proxy.post("/issueBill/editAddress", formInformation.data).then(() => {
        openInformation.value = false;
        ElMessage({ message: "保存成功", type: "success" });
        getList();
      });
    }
  });
};
const openExpress = ref(false);
const formExpress = reactive({
  data: {
    id: "",
    expressDeliveryId: "",
  },
});
const rulesExpress = ref({
  expressDeliveryId: [{ required: true, message: "请选择快递", trigger: "change" }],
});
const clickModifiedExpress = () => {
  if (selectData.value && selectData.value.length > 0) {
    if (selectData.value.length > 1) {
      return ElMessage("每次只能选一个");
    }
    formExpress.data = {
      id: selectData.value[0].id,
      expressDeliveryId: selectData.value[0].expressDeliveryId,
    };
    openExpress.value = true;
  } else {
    return ElMessage("请先选择需要修改快递的订单");
  }
};
const submitExpress = () => {
  proxy.$refs.refExpress.validate((valid) => {
    if (valid) {
      proxy.post("/issueBill/editExpressDeliveryId", formExpress.data).then(() => {
        openExpress.value = false;
        ElMessage({ message: "保存成功", type: "success" });
        getList();
      });
    }
  });
};
const clickPrint = () => {
  console.log("打印快递单");
};
const openExpressCode = ref(false);
const formExpressCode = reactive({
  data: {
    id: "",
    expressDeliveryCode: "",
  },
});
const rulesExpressCode = ref({
  expressDeliveryCode: [{ required: true, message: "请输入快递单号", trigger: "blur" }],
});
const clickFillInExpressCode = () => {
  if (selectData.value && selectData.value.length > 0) {
    if (selectData.value.length > 1) {
      return ElMessage("每次只能选一个");
    }
    formExpressCode.data = {
      id: selectData.value[0].id,
      expressDeliveryCode: selectData.value[0].expressDeliveryCode,
    };
    openExpressCode.value = true;
  } else {
    return ElMessage("请先选择需要填写快递单号的订单");
  }
};
const submitExpressCode = () => {
  proxy.$refs.refExpressCode.validate((valid) => {
    if (valid) {
      proxy.post("/issueBill/editExpressDeliveryCode", formExpressCode.data).then(() => {
        openExpressCode.value = false;
        ElMessage({ message: "保存成功", type: "success" });
        getList();
      });
    }
  });
};
</script>

<style lang="scss" scoped>
::v-deep(.remark) {
  margin: 0 16px;
  p {
    margin-block-start: 0 !important;
    margin-block-end: 0 !important;
  }
}
:deep(.el-dialog) {
  margin-top: 10px !important;
  margin-bottom: 10px !important;
}
</style>