<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 = false)"

    >
      <template #wareId="{ item }">
                     <span v-if="item.exDesc=='1'">
                     <svg-icon icon-class="jdyl" style="width: 34px;"/>
                </span>
        <span v-if="item.exDesc=='2'">
                     <svg-icon icon-class="jdks" style="width: 34px;"/>
                </span>
        <span
            :style="item.productName=='' || item.productName == undefined || item.productName == 'undefined'?'color: red':''">
                  {{item.wareId}}
                </span>
      </template>
      <template #wareName="{ item }">
        <span
            :style="item.productName=='' || item.productName == undefined || item.productName == 'undefined'?'color: red':''">
                  {{item.wareName}}
                </span>
      </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">
                    <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%;" >
                <el-option v-for="item in abnormalHandleTypeChileDict" :key="item.value" :label="item.label" :value="item.value"/>
              </el-select>
            </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" style="width: 100%;" @change="(e)=>getProductList(e,2)">
            <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  style="width: 100%;">
            <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" style="width: 100%;" @change="(e)=>getProductList(e,1)">
            <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%;">
            <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"  placeholder="请输入快递单号" oninput="value=value.replace(/[^\d.]/g,'')"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark" v-if="remarkFlag">
          <el-input type="textarea" :rows="3" v-model="formData.data.remark"  placeholder="请输入备注" oninput="value=value.replace(/[^\d.]/g,'')"/>
        </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" size="large" :loading="submitLoading">确定</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 submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
  },
});

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


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

const abnormalStatusDictAll = ref([
    {value: '10',label: '仓库多发',chile:[{value: '101',label: '补单（扣库存）'}]},
    {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: '202',label: '仓库已发-补单（不扣库存）'},
  {  value: '203',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 = ""

  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" }],
});

const queryDialogVisible = ref(false);
const dialogVisible = ref(false);
const stepsActiveindex = 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: "京东采购单号",
        prop: "orderId",
        align: "left",
        width: 120,
      },
    },
    {
      attrs: {
        label: "京东商品编号",
        slot: "wareId",
        align: "left",
        width: 175,
      },
    },
    {
      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 [
          row.handleStatus !== '2'
            ? {
                attrs: {
                  label: "处理",
                  type: "danger",
                  text: true,
                },
                el: "button",
                click() {
                  // ElMessageBox.confirm("是否确认当前采购单状态?", "提示", {
                  //   confirmButtonText: "确定",
                  //   cancelButtonText: "取消",
                  //   type: "warning",
                  // }).then(() => {
                  openHandleAction(row);
                  // });
                },
              }
            : {},
        ];
      },
    },
  ];
});

let formData = 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 getProductList = async (e,type) =>{
  proxy.post("/stock/pageByWarehouse", { pageNum: 1, pageSize: 999 ,id:e}).then((res) => {
    if (res.rows && res.rows.length > 0) {
      const product = res.rows.map((item) => {
        return {
          label: item.productName,
          value: item.productId,
        };
      });
      if (type == 1){
       addProductList.value = product
      } else {
       reduceProductList.value = product

      }
    }
  });


}

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.purchaseStartTime =
      sourceList.value.pagination.arr[0];
    sourceList.value.pagination.purchaseEndTime =
      sourceList.value.pagination.arr[1];
  }
  queryDialogVisible.value = false;
  getList();
};


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

    intiFlag()

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

    formData.data = {
      id:row.id,
      reduceQuantity  : absoluteValue,
      addQuantity  : absoluteValue,
    }

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

};
/**
 * 确认采购单状态
 * @param row
 */
const closeHandleAction = () => {
    dialogVisible.value = false;
    stepsActiveindex.value = 1
};

const tipsFlag = ref(false)
const reduceFlag = ref(false)
const addFlag = ref(false)
const remarkFlag = ref(false)
const deliveryFlag = ref(false)

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


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

  intiFlag()

  //判断 出库
  if (['101','402','403'].indexOf(type)>-1){
    reduceFlag.value = true
  }
  //判断 入库
  if (['301','401','402','403','501'].indexOf(type)>-1){
    addFlag.value = true
  }

  //判断 备注
  if (['201','203','403','503'].indexOf(type)>-1){
    remarkFlag.value = true
  }

  //判断 快递
  if (['401','501'].indexOf(type)>-1){
    deliveryFlag.value = true
  }

  //判断 提示
  if (['101','202','402','502'].indexOf(type)>-1){
    tipsFlag.value = true
  }

  stepsActiveindex.value++
}
const back = () => {
  stepsActiveindex.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;
          }
      );
    });
  }


}

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>
