<template>
  <div class="tenant">
    <byTable :source="sourceList.data" :pagination="sourceList.pagination" :config="config" :loading="loading" highlight-current-row
             :selectConfig="selectConfig" :table-events="{
                    select: select,
                }" :action-list="[]" @get-list="getList" @moreSearch="() => (queryDialogVisible = true)">
    </byTable>
    <!--回告-->
    <el-dialog :z-index="1500" title="采购单回告" v-if="tellDialogVisible" v-model="formData.data" width="1500px" v-loading="loading">
      <el-descriptions title="基础信息" />
      <el-form label-width="auto" :rules="rules">
        <el-row>
          <el-col :span="8">
            <el-form-item label="采购单号：" :span="8">
              {{formData.data.orderId}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="配送中心：" :span="8">
              {{formData.data.deliverCenterName}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库时间：" :span="8">
              {{formData.data.storageTime}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="预计送货时间：" :span="8">
              <el-date-picker v-model="formData.data.deliveryTime" type="datetime" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                              placeholder="请选择预计送货时间" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-descriptions title="采购单明细" />
          <el-table :data="formData.data.jdOrderDetailsList" stripe style="width: 100%">
            <!--            <el-table stripe style="width: 100%">-->
            <el-table-column prop="wareId" label="京东商品编号" width="180">
              <template #default="scope">
                <span
                      :style="scope.row.productName=='' || scope.row.productName == undefined || scope.row.productName == 'undefined'?'color: red':''">{{scope.row.wareId}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="wareName" label="京东商品名称">
              <template #default="scope">
                <span
                      :style="scope.row.productName=='' || scope.row.productName == undefined || scope.row.productName == 'undefined'?'color: red':''">{{scope.row.wareName}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="产品名称" />
            <el-table-column prop="originalNum" label="采购数量" />
            <el-table-column prop="confirmNum" label="确认数量">
              <template v-slot="scope">
                <el-form-item :rules="rules['confirmNum']">
                  <el-input-number :min="0" :step="1" :max="scope.row.originalNum" v-model="scope.row.confirmNum" placeholder="请输入确认数量" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="purchasePrice" label="采购价" />
            <el-table-column prop="nonDeliveryReason" label="不满足发货原因">
              <template v-slot="scope">
                <el-form-item :rules="rules['nonDeliveryReason']">
                  <el-input v-model="scope.row.nonDeliveryReason" placeholder="请输入不满足发货原因" />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="tellDialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitForm" size="large" :loading="submitLoading">采购单回告</el-button>
      </template>
    </el-dialog>

    <!--详情-->
    <el-dialog :z-index="1500" title="采购单详情" v-if="dialogVisible" v-model="formData.data" width="1500px" v-loading="loading">
      <el-descriptions title="基础信息" />
      <el-form label-width="auto" :rules="rules">
        <el-row>
          <el-col :span="8">
            <el-form-item label="京东订单号：" :span="8">
              {{formData.data.orderId}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订购时间：" :span="8" label-position="right">
              {{formData.data.createdDate}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商名称：" :span="8">
              {{formData.data.providerName}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="采购总金额：" :span="8">
              {{formData.data.totalPrice}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="配送中心名称：" :span="8">
              {{formData.data.deliverCenterName}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购员姓名：" :span="8">
              {{formData.data.purchaserName}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="删除状态：" :span="8">
              {{formData.data.statusName}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否EPT定制：" :span="8">
              {{formData.data.isEptCustomized?'是':'否'}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单状态：" :span="8">
              {{formData.data.stateName}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="完成时间：" :span="8">
              {{formData.data.completedDate}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="账期：" :span="8">
              {{formData.data.accountPeriod}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收货负责人：" :span="8">
              {{formData.data.receiverName}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="收货电话：" :span="8">
              {{formData.data.warehousePhone}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="详细地址：" :span="8">
              {{formData.data.address}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购类型：" :span="8">
              {{formData.data.orderTypeName}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="订单属性：" :span="8">
              {{formData.data.orderAttributeName}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="回告状态：" :span="8">
              {{formData.data.confirmStateName}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="顾客单号：" :span="8">
              {{formData.data.customerOrderid}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="品种数量：" :span="8">
              {{formData.data.wareVariety}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预计到货时间：" :span="8">
              {{formData.data.deliveryTime}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否可回告：" :span="8">
              {{formData.data.isCanConfirm?"可回告":"不可回告"}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="是否有差异：" :span="8">
              {{formData.data.isExistActualNumDif=='0'?"存在差异":"无差异"}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否已结算：" :span="8">
              {{formData.data.balanceStatus?"已结算":"未结算"}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库时间：" :span="8">
              {{formData.data.storageTime}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="TC转运标识：" :span="8">
              {{formData.data.tcFlagName}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预约时间：" :span="8">
              {{formData.data.bookTime}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-descriptions title="采购单明细" />
          <el-table :data="formData.data.jdOrderDetailsList" stripe style="width: 100%">
            <!--            <el-table stripe style="width: 100%">-->
            <el-table-column prop="wareId" label="京东商品编号" width="120">
              <template #default="scope">
                <span
                      :style="scope.row.productName=='' || scope.row.productName == undefined || scope.row.productName == 'undefined'?'color: red':''">{{scope.row.wareId}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="wareName" label="京东商品名称" min-width="200">
              <template #default="scope">
                <span
                      :style="scope.row.productName=='' || scope.row.productName == undefined || scope.row.productName == 'undefined'?'color: red':''">{{scope.row.wareName}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="产品名称" width="150" />
            <el-table-column prop="deliverCenterName" label="配送中心名称" width="110" />
            <el-table-column prop="purchasePrice" label="采购价" width="80" />
            <el-table-column prop="originalNum" label="原始采购数量" width="110" />
            <el-table-column prop="confirmNum" label="回告数量" width="80" />
            <el-table-column prop="actualNum" label="实收数量" width="80" />
            <el-table-column prop="nonDeliveryReason" label="不满足原因" width="100" />
            <el-table-column prop="totalPrice" label="采购总金额" width="110" />
            <el-table-column prop="storeName" label="库房名称" width="180" />
            <el-table-column prop="wareProperty" label="EPT采购单定制相关信息" width="180" />
          </el-table>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
      </template>
    </el-dialog>

    <!--高级搜索-->
    <el-dialog :title="'高级检索'" v-model="queryDialogVisible" width="500px" destroy-on-close>
      <el-form :model="sourceList.pagination" label-width="100px" label-position="top">
        <el-form-item label="采购单号">
          <el-input v-model="sourceList.pagination.orderId" placeholder="请输入采购单号" oninput="value=value.replace(/[^\d.]/g,'')"/>
        </el-form-item>
        <el-form-item label="京东商品编号">
          <el-input v-model="sourceList.pagination.wareId" placeholder="请输入京东商品编号" oninput="value=value.replace(/[^\d.]/g,'')"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleReset" size="large">重置</el-button>
        <el-button @click="handleQuery" type="primary" size="large">搜索</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 { computed, nextTick, reactive, ref } from "vue";
const { proxy } = getCurrentInstance();

const router = useRouter();
const loading = ref(false);
const deliveryCenter = ref([]);
const confirmState = ref([]);
const orderState = ref([]);

const blessingTypeList = ref([]);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
  },
});

let rules = ref({
  deliverCenterId: [
    { required: true, message: "请选择配送中心", trigger: "blur" },
  ],
  nonDeliveryReason: [
    { required: true, message: "请输入不满足发货原因", trigger: "blur" },
  ],
  confirmNum: [{ required: true, message: "请输入确认数量", trigger: "blur" }],
});

const queryDialogVisible = ref(false);
const dialogVisible = ref(false);
const tellDialogVisible = ref(false);

let modalType = ref("add");
const selectConfig = computed(() => {
  return [
    {
      label: "订单状态",
      prop: "state",
      data: orderState.value,
    },
    {
      label: "回告状态",
      prop: "confirmState",
      data: confirmState.value,
    },
    {
      label: "是否确认",
      prop: "businessStatus",
      data: [
        {
          label: "未确认",
          value: "0",
        },
        {
          label: "已确认",
          value: "1",
        },
        {
          label: "已回告",
          value: "2",
        },
      ],
    },
    {
      label: "是否可回告",
      prop: "isCanConfirm",
      data: [
        {
          label: "可回告",
          value: true,
        },
        {
          label: "不可回告",
          value: false,
        },
      ],
    },
  ];
});

const config = computed(() => {
  return [
    {
      attrs: {
        label: "京东订单号",
        align: "left",
        width: 120,
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: row.orderId,
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              getDtl(row);
            },
          },
        ];
      },
    },
    {
      attrs: {
        label: "订购时间",
        prop: "createdDate",
        align: "left",
        width: 170,
      },
    },
    {
      attrs: {
        label: "供应商名称",
        prop: "providerName",
        align: "left",
        width: 220,
      },
    },
    {
      attrs: {
        label: "采购总金额",
        prop: "totalPrice",
        align: "left",
        width: 110,
      },
      render(totalPrice) {
        return proxy.moneyFormat(totalPrice, 2);
      },
    },
    {
      attrs: {
        label: "配送中心名称",
        prop: "deliverCenterName",
        align: "left",
        width: 110,
      },
    },
    {
      attrs: {
        label: "订单状态",
        prop: "state",
        align: "left",
        width: 80,
      },
      render(value) {
        return proxy.dictValueLabel(value, orderState.value);
      },
    },
    {
      attrs: {
        label: "回告状态",
        prop: "confirmState",
        align: "left",
        width: 80,
      },
      render(value) {
        return proxy.dictValueLabel(value, confirmState.value);
      },
    },
    {
      attrs: {
        label: "是否可回告",
        prop: "isCanConfirm",
        align: "left",
        width: 100,
      },
      render(value) {
        return value ? "可回告" : "不可回告";
      },
    },
    {
      attrs: {
        label: "详细地址",
        prop: "address",
        align: "left",
        "min-width": 200,
      },
    },
    {
      attrs: {
        label: "采购类型",
        prop: "orderTypeName",
        align: "left",
        width: 100,
      },
    },
    {
      attrs: {
        label: "是否确认",
        prop: "businessStatus",
        align: "left",
        width: 80,
      },
      render(value) {
        let label = "未确认";
        if (value == "1") {
          label = "已确认";
        } else if (value == "2") {
          label = "已回告";
        }
        return label;
      },
    },
    {
      attrs: {
        label: "操作",
        width: "150",
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          //   {
          //     attrs: {
          //       label: "详情",
          //       type: "primary",
          //       text: true,
          //     },
          //     el: "button",
          //     click() {
          //       getDtl(row);
          //     },
          //   },
          row.businessStatus == 0
            ? {
                attrs: {
                  label: "采购单确认",
                  type: "danger",
                  text: true,
                },
                el: "button",
                click() {
                  ElMessageBox.confirm("是否确认当前采购单状态?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                  }).then(() => {
                    confirmBusinessStatus(row);
                  });
                },
              }
            : {},
          row.businessStatus == 1 && row.isCanConfirm
            ? {
                attrs: {
                  label: "回告",
                  type: "danger",
                  text: true,
                },
                el: "button",
                click() {
                  getTellDtl(row);
                },
              }
            : {},
        ];
      },
    },
  ];
});

let formData = reactive({
  data: {
    coverList: [],
    audioList: [],
  },
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);

const formConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "orderId",
      label: "京东订单号",
      readonly: true,
    },
    {
      type: "input",
      prop: "createdDate",
      label: "订购时间",
      readonly: true,
    },
    {
      type: "input",
      label: "采购单明细，应该是个一对多还没弄",
      readonly: true,
    },
  ];
});

const getDictlist = async () => {
  proxy
    .getDictOne(["delivery_center", "confirmState", "OrderState"])
    .then((res) => {
      deliveryCenter.value = res["delivery_center"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
      confirmState.value = res["confirmState"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
      orderState.value = res["OrderState"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
    });
};

const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/jdOrder/page", sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};

const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formData.data = {
    content: "",
  };
};
const selection = ref({
  data: [],
});
const select = (_selection, row) => {
  selection.value.data = _selection;
};

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

const getTellDtl = (row) => {
  modalType.value = "edit";
  proxy.post("/jdOrder/detail", { id: row.id }).then((res) => {
    formData.data = res;
    tellDialogVisible.value = true;
  });
};

/**
 * 确认采购单状态
 * @param row
 */
const confirmBusinessStatus = (row) => {
  let businessStatus = row.businessStatus == "1" ? 0 : 1;
  proxy
    .post("/jdOrder/confirmBusinessStatus", {
      id: row.id,
      businessStatus: businessStatus,
    })
    .then(
      () => {
        ElMessage({
          message: "确认成功",
          type: "success",
        });
        dialogVisible.value = false;
        submitLoading.value = false;
        getList();
      },
      (err) => {
        console.log(err);
        submitLoading.value = false;
      }
    );
};

//订单回告
const submitForm = () => {
  ElMessageBox.confirm("是否确认回告当前采购单?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    submitLoading.value = true;
    //TODO 这里应该是订单回告
    proxy.post("/jdOrder/tellBackOrer", formData.data).then(
      () => {
        ElMessage({
          message: "回告成功",
          type: "success",
        });
        tellDialogVisible.value = false;
        submitLoading.value = false;
        getList();
      },
      (err) => {
        console.log(err);
        submitLoading.value = false;
      }
    );
  });
};

//高级搜索
const handleReset = () => {
  sourceList.value.pagination = {
    pageNum: sourceList.value.pagination.pageNum,
    pageSize: sourceList.value.pagination.pageSize,
    arr: [],
  };
  handleQuery();
};

const handleQuery = () => {
  if (
    sourceList.value.pagination.arr &&
    sourceList.value.pagination.arr.length > 1
  ) {
    sourceList.value.pagination.purchaseStartTime =
      sourceList.value.pagination.arr[0];
    sourceList.value.pagination.purchaseEndTime =
      sourceList.value.pagination.arr[1];
  }
  queryDialogVisible.value = false;
  getList();
};

getDictlist();
getList();
</script>

<style lang='scss' scoped>
.tenant {
  padding: 20px;
}
:deep(.el-form-item--default) {
  margin-bottom: 0px;
}
</style>
