<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事件都能传
          select: select,
        }"
        :action-list="[
          {
            text: '添加物流数据',
            action: () => openModal('add'),
          },
        ]"
        @get-list="getList"
      >
        <template #one="{ item }">
          <div
            style="cursor: pointer; color: #409eff"
            @click="handleClickLinkCode(item)"
          >
            {{ item.businessCode }}
          </div>
        </template>
        <template #two="{ item }">
          <div
            style="cursor: pointer; color: #409eff"
            @click="handleClickCode(item)"
          >
            {{ item.code }}
          </div>
        </template>
      </byTable>
    </div>
    <el-dialog
      :title="
        modalType == 'add'
          ? '添加物流数据'
          : modalType == 'edit'
          ? '编辑物流数据'
          : '到货通知'
      "
      v-model="dialogVisible"
      width="800"
      v-loading="loading"
    >
      <byForm
        v-if="modalType != 'other'"
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="byform"
      >
      </byForm>
      <byForm
        v-else
        :formConfig="formConfigOne"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="byform"
      >
        <template #detailSlot>
          <div style="width: 100%">
            <el-table :data="formData.data.arrivalDetailList">
              <el-table-column
                prop="productDefinition"
                label="物品类型"
                :formatter="
                  (row) =>
                    row.productDefinition == 1
                      ? '产品'
                      : row.productDefinition == 2
                      ? '物料'
                      : ''
                "
              />
              <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="count" label="采购数量" />
              <el-table-column prop="transitQuantity" label="剩余在途" />
              <el-table-column prop="deliverGoodsQuantity" label="本次发货" />
            </el-table>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm('byform')"
          size="large"
          :loading="submitLoading"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>

    <el-dialog
      title="物流数据"
      v-model="openRecord"
      width="40%"
      top="50px"
      destroy-on-close
    >
      <!-- <div style="padding-left: 40px; margin-bottom: 20px">
        <el-button size="mini" @click="handleAddRecord">
          添加物流记录
        </el-button>
      </div> -->
      <div>
        <el-timeline :reverse="false">
          <el-timeline-item
            placement="top"
            v-for="(activity, index) in activities"
            :key="index"
            :timestamp="activity.ftime"
          >
            {{ activity.context }}
          </el-timeline-item>
        </el-timeline>
      </div>
      <template #footer>
        <el-button @click="openRecord = false" size="large">关闭</el-button>
      </template>
    </el-dialog>

    <el-dialog
      :title="'到货详情'"
      v-model="dialogVisibleOne"
      width="80%"
      destroy-on-close
    >
      <byForm
        :formConfig="formConfigTwo"
        :formOption="formOption"
        v-model="formData.dataOne"
        :rules="rules"
        ref="byformOne"
      >
        <template #detailSlot>
          <div style="width: 100%">
            <el-table :data="formData.dataOne.purchaseDetailVoList">
              <el-table-column prop="productCustomCode" label="物品编码" />
              <el-table-column prop="productName" label="物品名称" />
              <el-table-column prop="count" label="采购数量" />
              <el-table-column prop="deliverGoodsQuantity" label="已发货">
                <template #default="{ row }">
                  <div>
                    <el-popover
                      placement="bottom-start"
                      title="发货详情"
                      :width="500"
                      trigger="hover"
                    >
                      <div default>
                        <el-table :data="row.deliverGoodsDetailList">
                          <el-table-column
                            label="发货时间"
                            prop="createTime"
                            width="155"
                          />
                          <el-table-column
                            label="物流单号"
                            prop="logisticsCode"
                          />
                          <el-table-column
                            label="数量"
                            prop="deliverGoodsQuantity"
                            width="100"
                          />
                        </el-table>
                      </div>
                      <template #reference>
                        <div style="cursor: pointer; color: #0084ff">
                          {{ row.deliverGoodsQuantity }}
                        </div>
                      </template>
                    </el-popover>
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="receiptQuantity" label="已入库">
                <template #default="{ row }">
                  <div>
                    <el-popover
                      placement="bottom-start"
                      title="入库详情"
                      :width="500"
                      trigger="hover"
                    >
                      <div default>
                        <el-table :data="row.receiptList">
                          <el-table-column
                            label="入库时间"
                            prop="createTime"
                            width="155"
                          />
                          <el-table-column
                            label="入库单号"
                            prop="logisticsCode"
                          />
                          <el-table-column
                            label="数量"
                            prop="quantity"
                            width="100"
                          />
                        </el-table>
                      </div>
                      <template #reference>
                        <div style="cursor: pointer; color: #0084ff">
                          {{ row.receiptQuantity }}
                        </div>
                      </template>
                    </el-popover>
                  </div>
                </template>
              </el-table-column>

              <el-table-column prop="purchaseBackQuantity" label="退货">
                <template #default="{ row }">
                  <div>
                    <el-popover
                      placement="bottom-start"
                      title="退货详情"
                      :width="500"
                      trigger="hover"
                    >
                      <div default>
                        <el-table :data="row.purchaseBackDetailsList">
                          <el-table-column label="申请时间" prop="createTime" />
                          <el-table-column label="申请数量" prop="quantity" />
                          <el-table-column
                            label="已退数量"
                            prop="returnedQuantity"
                          />
                        </el-table>
                      </div>
                      <template #reference>
                        <div style="cursor: pointer; color: #0084ff">
                          {{ row.purchaseBackQuantity }}
                        </div>
                      </template>
                    </el-popover>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="qualityQuantity" label="已质检数量" />
              <el-table-column prop="noQualifiedCount" label="不合格数量" />
            </el-table>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisibleOne = false" size="large"
          >取 消</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup>
/* eslint-disable vue/no-unused-components */
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import { computed, defineComponent, ref } from "vue";
import useUserStore from "@/store/modules/user";
import SelectProduct from "@/components/WDLY/product/SelectProduct";
const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
  },
});
let dialogVisible = ref(false);
let dialogVisibleOne = ref(false);
let openProduct = ref(false);
let openRecord = ref(false);
const activities = ref([]);
let roomDialogVisible = ref(false);
let modalType = ref("add");
let rules = ref({
  businessType: [
    { required: true, message: "请选择数据来源", trigger: "change" },
  ],
  logisticsCompanyCode: [
    { required: true, message: "请选择物流/快递公司", trigger: "change" },
  ],
  code: [{ required: true, message: "请输入物流/快递单号", trigger: "blur" }],
  isKd100: [{ required: true, message: "请选择是否同步", trigger: "change" }],
});
const { proxy } = getCurrentInstance();
const statusData = ref([
  {
    label: "在途",
    value: "0",
  },
  {
    label: "揽收",
    value: "1",
  },
  {
    label: "疑难",
    value: "2",
  },
  {
    label: "签收",
    value: "3",
  },
  {
    label: "退签",
    value: "4",
  },
  {
    label: "派件",
    value: "5",
  },
  {
    label: "退回",
    value: "6",
  },
  {
    label: "转投",
    value: "7",
  },
  {
    label: "清关",
    value: "8",
  },
  {
    label: "拒签",
    value: "14",
  },
  {
    label: "完成",
    value: "15",
  },
]);
const businessType = ref([
  {
    dictValue: "采购入库",
    dictKey: "1",
  },
  {
    dictValue: "京东订单出库",
    dictKey: "2",
  },
  {
    dictValue: "销售订单出库",
    dictKey: "3",
  },
  {
    dictValue: "京东退货",
    dictKey: "4",
  },
  {
    dictValue: "采购退货",
    dictKey: "5",
  },
]);
const deptData = ref([]);
const selectConfig = computed(() => [
  {
    label: "数据来源",
    prop: "businessType",
    data: businessType.value,
  },
  {
    label: "物流状态",
    prop: "logisticsStatus",
    data: statusData.value,
  },
  {
    label: "项目组",
    prop: "deptId",
    data: deptData.value,
  },
]);
const config = computed(() => {
  return [
    {
      attrs: {
        label: "数据来源",
        prop: "businessType",
      },
      render(type) {
        return proxy.dictDataEcho(type, businessType.value);
      },
    },
    {
      attrs: {
        label: "关联单号",
        prop: "businessCode",
        slot: "one",
      },
    },
    {
      attrs: {
        label: "项目组",
        prop: "deptName",
        width: 150,
      },
    },
    {
      attrs: {
        label: "物流/快递公司",
        prop: "logisticsCompanyName",
      },
    },
    {
      attrs: {
        label: "物流/快递单号",
        prop: "code",
        slot: "two",
      },
    },
    {
      attrs: {
        label: "物流状态",
        prop: "logisticsStatus",
      },
      render(logisticsStatus) {
        let current = statusData.value.find((x) => x.value == logisticsStatus);
        return current ? current.label : "异常";
      },
    },
    {
      attrs: {
        label: "创建时间",
        prop: "createTime",
      },
    },

    {
      attrs: {
        label: "操作",
        width: "200",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "修改",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              getDtl(row);
            },
          },
          {
            attrs: {
              label: "更新状态",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              editStatus(row);
            },
          },
          row.businessType == 1
            ? {
                attrs: {
                  label: "到货通知",
                  type: "primary",
                  text: true,
                },
                el: "button",
                click() {
                  handleArrival(row);
                },
              }
            : {},
        ];
      },
    },
  ];
});
let formData = reactive({
  data: {},
  dataOne: {},
  treeData: [],
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const treeData = ref([]);
const formConfig = reactive([
  {
    type: "select",
    prop: "businessType",
    label: "数据来源",
    data: [],
    itemWidth: 61,
  },
  {
    type: "select",
    prop: "logisticsCompanyCode",
    label: "物流/快递信息",
    filterable: true,
    data: [],
    itemWidth: 40,
    style: {
      width: "100%",
    },
  },
  {
    type: "input",
    prop: "code",
    label: " ",
    itemWidth: 60,
  },
  {
    type: "radio",
    prop: "isKd100",
    label: "是否同步",
    required: true,
    border: true,
    data: [
      { label: "是", value: "1" },
      { label: "否", value: "2" },
    ],
  },
  {
    type: "input",
    prop: "remark",
    label: "备注",
    itemType: "textarea",
  },
]);
const formConfigOne = reactive([
  {
    type: "title",
    title: "基础信息",
  },
  {
    type: "input",
    prop: "supplyName",
    label: "供应商",
    disabled: true,
    itemWidth: 50,
  },
  {
    type: "input",
    prop: "purchaseCode",
    label: "采购单号",
    disabled: true,
    itemWidth: 50,
  },
  {
    type: "select",
    label: "物流/快递单号",
    prop: "code",
    itemWidth: 50,
    disabled: true,
    style: {
      width: "100%",
    },
  },
  {
    type: "slot",
    slotName: "detailSlot",
    label: "发货明细",
  },
]);

let formConfigTwo = computed(() => [
  {
    type: "title",
    title: "基础信息",
  },
  {
    type: "input",
    prop: "supplyName",
    label: "供应商",
    disabled: true,
    itemWidth: 50,
  },
  {
    type: "input",
    prop: "purchaseCode",
    label: "采购单号",
    disabled: true,
    itemWidth: 50,
  },
  {
    type: "title",
    title: "采购明细",
  },
  {
    type: "slot",
    slotName: "detailSlot",
    label: "",
  },
]);

const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/logisticsInfos/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 openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formConfig[0].disabled = false;
  formData.data = {
    isKd100: "1",
  };
};

const submitForm = () => {
  console.log(byform.value);
  byform.value.handleSubmit((valid) => {
    if (modalType.value == "other") {
      loading.value = true;
      submitLoading.value = true;
      formData.data.arrivalDetailList = formData.data.arrivalDetailList.map(
        (x) => ({
          bussinessId: x.bussinessId,
          purchaseDetailId: x.purchaseDetailId,
          deliverGoodsDetailsId: x.deliverGoodsDetailsId,
          count: x.deliverGoodsQuantity,
        })
      );
      const victoriatouristJson = {
        deliverGoodsId: formData.data.deliverGoodsId,
        logisticsCompanyCode: formData.data.logisticsCompanyCode,
        code: formData.data.code,
      };
      formData.data.victoriatouristJson = JSON.stringify(victoriatouristJson);
      proxy.post("/arrival/addByWdly", formData.data).then(
        (res) => {
          ElMessage({
            message: `操作成功！`,
            type: "success",
          });
          dialogVisible.value = false;
          loading.value = false;
          getList();
        },
        (err) => (submitLoading.value = false)
      );
    } else {
      loading.value = true;
      submitLoading.value = true;
      proxy.post("/logisticsInfos/" + modalType.value, formData.data).then(
        (res) => {
          ElMessage({
            message: modalType.value == "add" ? "添加成功" : "编辑成功",
            type: "success",
          });
          dialogVisible.value = false;
          submitLoading.value = false;
          getList();
        },
        (err) => (submitLoading.value = false)
      );
    }
  });
};

const getDtl = (row) => {
  modalType.value = "edit";
  proxy.post("/logisticsInfos/detail", { id: row.id }).then((res) => {
    formConfig[0].disabled = true;
    formData.data = {
      id: res.id,
      businessType: res.businessType + "",
      logisticsCompanyCode: res.logisticsCompanyCode,
      code: res.code,
      isKd100: res.isKd100 + "",
      remark: "",
    };
    dialogVisible.value = true;
  });
};
const editStatus = (row) => {
  ElMessageBox.confirm("是否确定进行此操作?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // 删除
    proxy
      .post("/logisticsInfos/dataInfoEdit", {
        id: row.id,
      })
      .then((res) => {
        ElMessage({
          message: "更新成功",
          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[1].data = logisticsData.value.map((x) => ({
      label: x.name,
      value: x.code,
    }));
  });
};
const handleClickCode = (row) => {
  let id = row.id;
  proxy.post("/logisticsInfos/getLogistics", { id }).then((res) => {
    if (res.data && res.data.length > 0) {
      activities.value = res.data;
      openRecord.value = true;
    } else {
      return ElMessage({
        message: res.message,
        type: "info",
      });
    }
  });
};

const deliverData = ref([]);
const handleArrival = (row) => {
  modalType.value = "other";
  proxy.post("/deliverGoods/detail", { id: row.businessId }).then((res) => {
    formData.data = {
      purchaseId: row.id,
      businessId: row.id,
      supplyName: row.supplyName,
      purchaseCode: row.businessCode,
      supplyId: row.supplyId,
      code: row.code,
      logisticsCompanyCode: row.logisticsCompanyCode,
      deliverGoodsId: res[0] ? res[0].deliverGoodsId : "",
      arrivalDetailList: res.map((x) => ({
        count: x.count,
        productName: x.name,
        productSpec: x.spec,
        productUnit: x.unit,
        productType: x.type,
        productCode: x.code,
        bussinessId: x.productId,
        purchaseDetailId: x.purchaseDetailId,
        deliverGoodsDetailsId: x.id,
        transitQuantity: x.transitQuantity,
        deliverGoodsQuantity: x.deliverGoodsQuantity,
        productDefinition: x.definition,
      })),
    };
    dialogVisible.value = true;
  });
};
const handleClickLinkCode = (row) => {
  if (row.businessType == 1 || row.businessType == 5) {
    ElMessage({
      message: "数据请求中，请稍后",
      type: "info",
    });
    proxy
      .post("/deliverGoods/arrivalDetail", { purchaseId: row.purchaseId })
      .then((res) => {
        formData.dataOne = {
          supplyName: res.supplyName,
          purchaseCode: row.businessCode,
          purchaseDetailVoList: res.purchaseDetailVoList,
        };
        dialogVisibleOne.value = true;
      });
  }
};
const getDict = () => {
  proxy.get("/logisticsInfos/getDepts").then((res) => {
    deptData.value = res.data.map((x) => ({
      ...x,
      label: x.deptName,
      value: x.deptId,
    }));
  });
};
getDict();
getList();
getLogisticsData();
onMounted(() => {
  formConfig[0].data = businessType.value.map((x) => ({
    label: x.dictValue,
    value: x.dictKey,
  }));
});
</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>