<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)">
      <template #orderId="{ item }">
        <div style="display: flex; justify-content: flex-start;line-height: 34px;height: 34px" @click="getDtl(item);">
          <!--          <div v-if="item.hasEx=='1'">-->
          <!--            <img src="@/assets/images/jdyc.png" alt=""  style="width: 34px"/>-->
          <!--          </div>-->
          <!--          <div v-else style="width: 34px">-->

          <!--          </div>-->
          <span style="color: blue">{{item.orderId}}</span>
        </div>
      </template>

      <template #wareId="{ item }">
        <div style="display: flex; justify-content: center;line-height: 34px;height: 34px">
          <div v-if="item.exDesc=='1'">
            <img src="@/assets/images/jdsh.png" alt="" style="width: 34px" />
          </div>
          <div v-if="item.exDesc=='2'">
            <img src="@/assets/images/jddh.png" alt="" style="width: 34px" />
          </div>
          <div :style="item.productName=='' || item.productName == undefined || item.productName == 'undefined'?'color: red':''">
            {{item.wareId}}
          </div>
        </div>

      </template>
      <template #wareName="{ item }">
        <span :style="item.productName=='' || item.productName == undefined || item.productName == 'undefined'?'color: red':''">
          {{item.wareName}}
        </span>
      </template>
      <template #abnormalStatus="{ item }">
        {{showAbnormalStatus(item)}}
      </template>
      <template #exHandle="{ item }">
        {{showExHandle(item)}}
      </template>
    </byTable>

    <!--详情-->
    <el-dialog :z-index="1500" title="异常处理" v-if="dialogVisible" v-model="formData.data" width="500px" v-loading="loading" @close="closeHandleAction">
      <el-steps :active="stepsActiveindex" align-center>
        <el-step title="选择异常场景"></el-step>
        <el-step title="处理异常明细"></el-step>
      </el-steps>
      <el-divider></el-divider>
      <el-form class="stepsActive1" :model="formData.data" ref="submitform" :rules="rules" style="margin-top: 0px;height: auto" label-position="top"
               label-width="100px" v-if="stepsActiveindex == 1">
        <el-form-item label="异常场景" prop="abnormalStatus">
          <el-select v-model="formData.data.abnormalStatus" style="width: 100%;" @change="treeChange" :disabled="isViewFlag">
            <el-option v-for="item in abnormalHandleTypeDict" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理方案" prop="exHandle">
          <el-select v-model="formData.data.exHandle" style="width: 100%;" :disabled="isViewFlag" @change="exHandleChange">
            <el-option v-for="item in abnormalHandleTypeChileDict" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="原京东采购单" prop="sourceOrderId" v-if="formData.data.abnormalStatus=='20' && formData.data.exHandle=='202'">
          <el-button type="primary" plain @click="selectOrder = true" style="margin-bottom:10px">选择</el-button>
          <el-input v-model="formData.data.sourceOrderCode" disabled></el-input>
        </el-form-item>

        <el-form-item label="差异商品数量" prop="absoluteValue">
          <el-input v-model="formData.data.absoluteValue" disabled placeholder="请输入出库商品数量" oninput="value=value.replace(/[^\d.]/g,'')" />
        </el-form-item>
      </el-form>
      <el-form class="stepsActive2" :model="formData.data" style="margin-top: 20px;height: auto" ref="submitform2" :rules="rules" label-position="top"
               label-width="100px" v-if="stepsActiveindex == 2">
        <el-form-item label="出库仓库" prop="reduceWarehouseId" v-if="reduceFlag">
          <el-select v-model="formData.data.reduceWarehouseId" :disabled="isViewFlag" style="width: 100%;">
            <el-option v-for="item in warehouseList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="出库商品" prop="reduceProductId" v-if="reduceFlag">
          <el-select v-model="formData.data.reduceProductId" filterable remote :disabled="reduceProductIdDisplay" style="width: 100%;"
                     :remote-method="remoteValue">
            <el-option v-for="item in reduceProductList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="出库商品数量" prop="reduceQuantity" v-if="reduceFlag">
          <el-input v-model="formData.data.reduceQuantity" disabled placeholder="请输入出库商品数量" oninput="value=value.replace(/[^\d.]/g,'')" />
        </el-form-item>

        <el-form-item label="入库仓库" prop="addWarehouseId" v-if="addFlag">
          <el-select v-model="formData.data.addWarehouseId" :disabled="isViewFlag" style="width: 100%;">
            <el-option v-for="item in warehouseList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="入库商品" prop="addProductId" v-if="addFlag">
          <el-select v-model="formData.data.addProductId" filterable style="width: 100%;" :disabled="addProductIdDisplay">
            <el-option v-for="item in addProductList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="入库商品数量" prop="addQuantity" v-if="addFlag">
          <el-input v-model="formData.data.addQuantity" disabled placeholder="请输入出库商品数量" oninput="value=value.replace(/[^\d.]/g,'')" />
        </el-form-item>

        <el-form-item label="快递单号" prop="expressNo" v-if="deliveryFlag">
          <el-input v-model="formData.data.expressNo" :disabled="isViewFlag" placeholder="请输入快递单号" />
        </el-form-item>

        <el-form-item label="金额" prop="amount" v-if="amountFlag">
          <el-input type="number" v-model="formData.data.amount" :disabled="isViewFlag" placeholder="请输入金额" />
        </el-form-item>
        <el-form-item label="备注" prop="remark" v-if="remarkFlag">
          <el-input type="textarea" :rows="3" :disabled="isViewFlag" v-model="formData.data.remark" placeholder="请输入备注" />
        </el-form-item>

        <span style="color: red" v-if="tipsFlag">*请到京东平台补单</span>
      </el-form>

      <template #footer>
        <el-divider></el-divider>
        <el-button @click="back" v-if="stepsActiveindex > 1 " size="large" :loading="submitLoading">上一步</el-button>
        <el-button @click="next" v-if="stepsActiveindex < 2 " size="large" :loading="submitLoading">下一步</el-button>
        <el-button @click="submit" v-if="stepsActiveindex ==2  &&  !isViewFlag" size="large" :loading="submitLoading">确定</el-button>
      </template>
    </el-dialog>

    <!--详情-->
    <el-dialog :z-index="1500" title="采购单详情" v-if="detailsDialogVisible" v-model="formData1.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">
              {{formData1.data.orderId}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订购时间：" :span="8" label-position="right">
              {{formData1.data.createdDate}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商名称：" :span="8">
              {{formData1.data.providerName}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="采购总金额：" :span="8">
              {{formData1.data.totalPrice}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="配送中心名称：" :span="8">
              {{formData1.data.deliverCenterName}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购员姓名：" :span="8">
              {{formData1.data.purchaserName}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="删除状态：" :span="8">
              {{formData1.data.statusName}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否EPT定制：" :span="8">
              {{formData1.data.isEptCustomized?'是':'否'}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单状态：" :span="8">
              {{formData1.data.stateName}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="完成时间：" :span="8">
              {{formData1.data.completedDate}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="账期：" :span="8">
              {{formData1.data.accountPeriod}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="收货负责人：" :span="8">
              {{formData1.data.receiverName}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="收货电话：" :span="8">
              {{formData1.data.warehousePhone}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="详细地址：" :span="8">
              {{formData1.data.address}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购类型：" :span="8">
              {{formData1.data.orderTypeName}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="订单属性：" :span="8">
              {{formData1.data.orderAttributeName}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="回告状态：" :span="8">
              {{formData1.data.confirmStateName}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="顾客单号：" :span="8">
              {{formData1.data.customerOrderid}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="品种数量：" :span="8">
              {{formData1.data.wareVariety}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预计到货时间：" :span="8">
              {{formData1.data.deliveryTime}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否可回告：" :span="8">
              {{formData1.data.isCanConfirm?"可回告":"不可回告"}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="是否有差异：" :span="8">
              {{formData1.data.isExistActualNumDif=='0'?"存在差异":"无差异"}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否已结算：" :span="8">
              {{formData1.data.balanceStatus?"已结算":"未结算"}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库时间：" :span="8">
              {{formData1.data.storageTime}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="TC转运标识：" :span="8">
              {{formData1.data.tcFlagName}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预约时间：" :span="8">
              {{formData1.data.bookTime}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-descriptions title="采购单明细" />
          <div style="line-height: 34px;height: 34px;display: flex">
            <span>（</span>
            <span><img src="@/assets/images/jdsh.png" alt="" style="width: 34px" /></span><span>多货</span>
            <span><img src="@/assets/images/jddh.png" alt="" style="width: 34px" /></span><span>少货</span>
            <span>）</span>
          </div>

          <el-table :data="formData1.data.jdOrderDetailsList" stripe style="width: 100%">
            <!--            <el-table stripe style="width: 100%">-->
            <el-table-column prop="wareId" label="京东商品编号" width="175">
              <template #default="scope">
                <div style="display: flex; justify-content: center;line-height: 34px;height: 34px">
                  <div v-if="scope.row.exDesc=='1'">
                    <img src="@/assets/images/jdsh.png" alt="" style="width: 34px" />
                  </div>
                  <div v-if="scope.row.exDesc=='2'">
                    <img src="@/assets/images/jddh.png" alt="" style="width: 34px" />
                  </div>
                  <div
                       :style="scope.row.productName=='' || scope.row.productName == undefined || scope.row.productName == 'undefined'?'color: red':''">
                    {{scope.row.wareId}}
                  </div>
                </div>

              </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="detailsDialogVisible = 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-date-picker v-model="sourceList.pagination.arr" type="daterange" range-separator="到" start-placeholder="请选择" end-placeholder="请选择"
                          value-format="YYYY-MM-DD HH:mm:ss" />
        </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>
    <el-dialog :title="'选择京东采购单'" v-model="selectOrder" width="90%" destroy-on-close>
      <JdOrder :selectStatus="true" @selectOrder="handleSelectOrder"></JdOrder>
    </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";
import { isNullOrUndefined } from "@tinymce/tinymce-vue/lib/es2015/main/ts/Utils";
import JdOrder from "@/views/WDLY/jd/order/index";

const { proxy } = getCurrentInstance();

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

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

const warehouseList = ref([]);
const reduceProductList = ref([]);
const addProductList = ref([]);
const productList = ref([]);

const abnormalHandleTypeDict = ref([]);
const abnormalHandleTypeChileDict = ref([]);

const abnormalStatusDictAll = ref([]);

const abnormalStatusDictDh = ref([
  {
    value: "10",
    label: "仓库多发",
    chile: [{ value: "101", label: "补单（扣库存）" }],
  },
]);

const abnormalStatusDictSh = ref([
  {
    value: "20",
    label: "仓库已发",
    chile: [
      { value: "201", label: "报损" },
      { value: "202", label: "补单（不扣库存）" },
      { value: "203", label: "索赔理赔" },
    ],
  },
  {
    value: "30",
    label: "仓库少发",
    chile: [{ value: "301", label: "退回库存" }],
  },
  {
    value: "40",
    label: "仓库发错货物",
    chile: [
      { value: "401", label: "货物退回" },
      { value: "402", label: "补单" },
      { value: "403", label: "报损" },
    ],
  },
  {
    value: "50",
    label: "条码错误",
    chile: [
      { value: "501", label: "货物退回" },
      { value: "502", label: "补单" },
      { value: "503", label: "报损" },
    ],
  },
]);
const abnormalStatusDict = ref([
  { value: "101", label: "仓库多发-补单（扣库存）" },
  { value: "201", label: "仓库已发-报损" },
  { value: "203", label: "仓库已发-索赔理赔" },
  { value: "202", label: "仓库已发-补单（不扣库存）" },
  { value: "301", label: "仓库少发-退回库存" },
  { value: "401", label: "仓库发错货物-货物退回" },
  { value: "402", label: "仓库发错货物-补单" },
  { value: "403", label: "仓库发错货物-报损" },
  { value: "501", label: "条码错误-货物退回" },
  { value: "502", label: "条码错误-补单" },
  { value: "503", label: "条码错误-报损" },
]);

const treeChange = (e) => {
  formData.data.exHandle = "";
  formData.data.sourceOrderId = "";
  formData.data.sourceOrderCode = "";

  treeChangeSelect(e);
};

const exHandleChange = () => {
  formData.data.sourceOrderId = "";
  formData.data.sourceOrderCode = "";
};

const treeChangeSelect = (e) => {
  const abnormalStatusDict = abnormalStatusDictAll.value.filter((x) => {
    return x.value == e;
  });
  abnormalHandleTypeChileDict.value = abnormalStatusDict[0].chile;
};

let rules = ref({
  abnormalStatus: [
    { required: true, message: "请选择异常状态", trigger: "change" },
  ],
  exHandle: [{ required: true, message: "请选择异常处理", trigger: "change" }],

  addWarehouseId: [
    { required: true, message: "请选择入库仓库", trigger: "change" },
  ],
  addProductId: [
    { required: true, message: "请选择入库商品", trigger: "change" },
  ],
  addQuantity: [{ required: true, message: "请填写入库数量", trigger: "blur" }],

  reduceWarehouseId: [
    { required: true, message: "请选择出库仓库", trigger: "change" },
  ],
  reduceProductId: [
    { required: true, message: "请选择出库商品", trigger: "change" },
  ],
  reduceQuantity: [
    { required: true, message: "请填写出库数量", trigger: "blur" },
  ],

  expressNo: [{ required: true, message: "请填写快递单号", trigger: "blur" }],
  remark: [{ required: true, message: "请填写备注", trigger: "blur" }],
  amount: [{ required: true, message: "请填写金额", trigger: "blur" }],
  sourceOrderId: [
    { required: true, message: "请选择原京东采购单", trigger: "blur" },
  ],
});

const queryDialogVisible = ref(false);
const detailsDialogVisible = ref(false);
const dialogVisible = ref(false);
const isViewFlag = ref(false);
const stepsActiveindex = ref(1);
const views = ref(1);

let modalType = ref("add");
const selectConfig = computed(() => {
  return [
    {
      label: "异常状态",
      prop: "exDesc",
      data: [
        {
          label: "多货",
          value: "1",
        },
        {
          label: "少货",
          value: "2",
        },
      ],
    },
    {
      label: "处理状态",
      prop: "handleStatus",
      data: [
        {
          label: "已处理",
          value: "2",
        },
        {
          label: "未处理",
          value: "1",
        },
      ],
    },
    {
      label: "处理方案",
      prop: "exHandle",
      data: abnormalStatusDict.value,
    },
  ];
});

const config = computed(() => {
  return [
    {
      attrs: {
        label: "京东采购单号",
        slot: "orderId",
        align: "left",
        width: 120,
      },
    },
    {
      attrs: {
        label: "京东商品编号",
        slot: "wareId",
        align: "left",
        width: 175,
      },
      // renderHTML(row) {
      //   return [
      //     {
      //       attrs: {
      //         label: row.orderId,
      //         type: "primary",
      //         text: true,
      //       },
      //       el: "button",
      //       click() {
      //         openHandleAction(row, true);
      //       },
      //     },
      //   ];
      // },
    },
    {
      attrs: {
        label: "原京东采购单",
        prop: "sourceOrderCode",
        align: "left",
        width: 110,
      },
    },
    {
      attrs: {
        label: "处理状态",
        prop: "handleStatus",
        align: "left",
        width: 100,
      },
      render(type) {
        return type == "2" ? "已处理" : "未处理";
      },
    },
    {
      attrs: {
        label: "异常场景",
        slot: "abnormalStatus",
        align: "left",
        width: 100,
      },
      render(type) {
        return type == "2" ? "已处理" : "未处理";
      },
    },
    {
      attrs: {
        label: "处理方案",
        slot: "exHandle",
        align: "left",
        width: 100,
      },
    },
    {
      attrs: {
        label: "金额",
        prop: "amount",
        align: "left",
        width: 100,
      },
    },
    {
      attrs: {
        label: "京东商品名称",
        slot: "wareName",
        align: "left",
        "min-width": 200,
      },
    },
    {
      attrs: {
        label: "产品名称",
        prop: "productName",
        align: "left",
        "min-width": 150,
      },
    },
    {
      attrs: {
        label: "配送中心名称",
        prop: "deliverCenterName",
        align: "left",
        width: 150,
      },
    },
    {
      attrs: {
        label: "采购价",
        prop: "purchasePrice",
        align: "left",
        width: 80,
      },
    },
    {
      attrs: {
        label: "原始采购数量",
        prop: "originalNum",
        align: "left",
        width: 110,
      },
    },
    {
      attrs: {
        label: "回告数量",
        prop: "confirmNum",
        align: "left",
        width: 80,
      },
    },
    {
      attrs: {
        label: "实收数量",
        prop: "actualNum",
        align: "left",
        width: 80,
      },
    },
    {
      attrs: {
        label: "不满足原因",
        prop: "nonDeliveryReason",
        align: "left",
        width: 100,
      },
    },
    {
      attrs: {
        label: "采购总金额",
        prop: "totalPrice",
        align: "left",
        width: 110,
      },
    },
    {
      attrs: {
        label: "库房名称",
        prop: "storeName",
        align: "left",
        width: 180,
      },
    },
    {
      attrs: {
        label: "EPT采购单定制相关信息",
        prop: "wareProperty",
        align: "left",
        width: 180,
      },
    },
    {
      attrs: {
        label: "操作",
        width: "150",
        align: "center",
        fixed: "right",
      },
      renderHTML(row) {
        return [
          !isNullOrUndefined(row.productName)
            ? {
                attrs: {
                  label: row.handleStatus == "1" ? "处理" : "详情",
                  type: "danger",
                  text: true,
                },
                el: "button",
                click() {
                  openHandleAction(row, row.handleStatus == "1" ? false : true);
                },
              }
            : {},
        ];
      },
    },
  ];
});

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

const getDictlist = async () => {
  proxy.post("/warehouse/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    if (res.rows && res.rows.length > 0) {
      warehouseList.value = res.rows.map((item) => {
        return {
          label: item.name,
          value: item.id,
        };
      });
    }
  });
};

const remoteValue = (query) => {
  console.log("query", query);
  if (query !== "") {
    proxy
      .post("/productInfo/page", {
        pageNum: 1,
        pageSize: 99999,
        keyword: query,
      })
      .then((res) => {
        if (res.rows && res.rows.length > 0) {
          reduceProductList.value = res.rows.map((item) => {
            return {
              label: item.name,
              value: item.id,
            };
          });
        }
      });
  } else {
    reduceProductList.value = [];
  }
};

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

const selection = ref({
  data: [],
});
const select = (_selection, row) => {
  selection.value.data = _selection;
};

//高级搜索
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.startTime = sourceList.value.pagination.arr[0];
    sourceList.value.pagination.endTime = sourceList.value.pagination.arr[1];
  }
  queryDialogVisible.value = false;
  getList();
};

/**
 * 确认采购单状态
 * @param row
 */
const openHandleAction = (row, isView) => {
  console.log("row", row.exDesc);
  dialogVisible.value = true;
  stepsActiveindex.value = 1;

  intiFlag();

  let absoluteValue = Math.abs(Number(row.confirmNum) - Number(row.actualNum));

  if (row.exDesc == "1") {
    abnormalStatusDictAll.value = abnormalStatusDictDh.value;
  } else if (row.exDesc == "2") {
    abnormalStatusDictAll.value = abnormalStatusDictSh.value;
  }

  abnormalHandleTypeDict.value = abnormalStatusDictAll.value.map((x) => {
    return {
      label: x.label,
      value: x.value,
    };
  });

  isViewFlag.value = isView;
  if (isView) {
    formData.data = row;
    //异常状态明细
    formData.data.abnormalStatus = row.exHandle.substring(0, 2);
    //处理方案
    treeChangeSelect(formData.data.abnormalStatus);
    formData.data.absoluteValue = absoluteValue;
  } else {
    formData.data = {
      id: row.id,
      reduceQuantity: absoluteValue,
      addQuantity: absoluteValue,
      absoluteValue: absoluteValue,
      productId: row.productId,
    };
  }
};
/**
 * 确认采购单状态
 * @param row
 */
const closeHandleAction = () => {
  dialogVisible.value = false;
  stepsActiveindex.value = 1;
};

const tipsFlag = ref(false);
const reduceFlag = ref(false);
const reduceProductIdDisplay = ref(false);
const addFlag = ref(false);
const addProductIdDisplay = ref(false);
const remarkFlag = ref(false);
const deliveryFlag = ref(false);
const amountFlag = ref(false);

const intiFlag = () => {
  tipsFlag.value = false;
  addFlag.value = false;
  reduceFlag.value = false;
  remarkFlag.value = false;
  amountFlag.value = false;
  deliveryFlag.value = false;
  reduceProductIdDisplay.value = false;
  addProductIdDisplay.value = false;
};

const next = async () => {
  let flag = await submitform.value.validate();
  const type = formData.data.exHandle;

  intiFlag();

  if (isViewFlag.value) {
    reduceProductIdDisplay.value = true;
    addProductIdDisplay.value = true;
  } else {
    formData.data.reduceProductId = null;
    formData.data.addProductId = null;
  }

  //判断 出库
  if (["101", "402", "403"].indexOf(type) > -1) {
    reduceFlag.value = true;
  }
  //判断 出库
  if (!isViewFlag.value) {
    if (["101"].indexOf(type) > -1) {
      formData.data.reduceProductId = formData.data.productId;
      reduceProductIdDisplay.value = true;
    }
  }
  //判断 入库
  if (["301", "401", "402", "403", "501"].indexOf(type) > -1) {
    addFlag.value = true;
  }
  //判断 入库
  if (!isViewFlag.value) {
    if (["301", "401", "402", "403", "501"].indexOf(type) > -1) {
      formData.data.addProductId = formData.data.productId;
      addProductIdDisplay.value = true;
    }
  }
  handProductList();
  //判断 备注
  if (["201", "203", "403", "503"].indexOf(type) > -1) {
    remarkFlag.value = true;
  }
  //判断 快递
  if (["401", "501"].indexOf(type) > -1) {
    deliveryFlag.value = true;
  }
  //判断 金额
  if (["201", "203", "403", "503"].indexOf(type) > -1) {
    amountFlag.value = true;
  }
  //判断 提示
  if (["101", "202", "402", "502"].indexOf(type) > -1) {
    tipsFlag.value = true;
  }

  stepsActiveindex.value++;
};
const back = () => {
  stepsActiveindex.value--;
};

const handProductList = () => {
  //preventValue  防止被认为 重复请求

  if (!isNullOrUndefined(formData.data.addProductId)) {
    proxy
      .post("/jdOrderEx/productInfoById", {
        productId: formData.data.addProductId,
        preventValue: 1,
      })
      .then((res) => {
        if (res && res.length > 0) {
          addProductList.value = res.map((item) => {
            return {
              label: item.name,
              value: item.id,
            };
          });
        }
      });
  } else {
    // addProductList.value = productList.value
  }
  if (!isNullOrUndefined(formData.data.reduceProductId)) {
    proxy
      .post("/jdOrderEx/productInfoById", {
        productId: formData.data.reduceProductId,
        preventValue: 2,
      })
      .then((res) => {
        if (res && res.length > 0) {
          reduceProductList.value = res.map((item) => {
            return {
              label: item.name,
              value: item.id,
            };
          });
        }
      });
  } else {
    // reduceProductList.value = productList.value
  }
};

const submit = async () => {
  let flag = await submitform2.value.validate();
  if (flag) {
    ElMessageBox.confirm("是否确认当前处理方法?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      submitLoading.value = true;

      proxy.post("/jdOrderEx/dealEx", formData.data).then(
        () => {
          ElMessage({
            message: "处理成功",
            type: "success",
          });
          dialogVisible.value = false;
          submitLoading.value = false;
          getList();
        },
        (err) => {
          console.log(err);
          submitLoading.value = false;
        }
      );
    });
  }
};

const showAbnormalStatus = (item) => {
  if (item.handleStatus != 2 || isNullOrUndefined(item.exHandle)) {
    return "";
  }
  let dict = [];
  if (item.exDesc == "1") {
    dict = abnormalStatusDictDh.value;
  } else if (item.exDesc == "2") {
    dict = abnormalStatusDictSh.value;
  }
  const abnormalStatus = item.exHandle.substring(0, 2);
  const abnormalStatusDict = dict.filter((x) => {
    return x.value == abnormalStatus;
  });
  return abnormalStatusDict[0].label;
};

const showExHandle = (item) => {
  if (item.handleStatus != 2 || isNullOrUndefined(item.exHandle)) {
    return "";
  }

  let dict = [];
  if (item.exDesc == "1") {
    dict = abnormalStatusDictDh.value;
  } else if (item.exDesc == "2") {
    dict = abnormalStatusDictSh.value;
  }
  const abnormalStatus = item.exHandle.substring(0, 2);
  const abnormalStatusDict = dict.filter((x) => {
    return x.value == abnormalStatus;
  });
  const exHandle = abnormalStatusDict[0].chile.filter((x) => {
    return x.value == item.exHandle;
  });

  return exHandle[0].label;
};

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

const selectOrder = ref(false);
const handleSelectOrder = (row) => {
  formData.data.sourceOrderId = row.id;
  formData.data.sourceOrderCode = row.orderId;
  ElMessage({
    message: "选择成功",
    type: "success",
  });
  selectOrder.value = false;
};

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

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

.stepsActive1 .el-form-item {
  margin-bottom: 20px;
}
.stepsActive2 .el-form-item {
  margin-bottom: 10px;
}
</style>
