<template>
  <div class="global-custom-page-wrap" data-key="ADD_COPY_JIT_D">
    <div class="global-public-quickOperation" data-key="ADD_COPY_JIT_D">
      快捷操作：
      <Button
        type="fcdefault"
        style="margin-right:8px" @click="saveAllHandle">保存</Button>
      <Button type="fcdefault" @click="jumpPage">关闭</Button>
    </div>
    <div id="customBaseFormWrap" class="global-custom-form-wrap">
      <panel-form
        ref="objform"
        style="flex:1"
        table-name="T_FILETYPE_ORDER"
        class="strategy-panel"
        display="flex"
        :label-width="210"
        :no-resize="true"
        :readonly="panelFormData.objreadonly"
        :is-main-table="panelFormData.isMainTable"
        :default-data="panelFormData.data"
        @on-changeForm="onChangeForm"
      />
    </div>
    <div class="global-custom-tab-wrap">
      <Tabs type="card" :value="activeName">
        <TabPane label="JIT配货单明细" name="detailOne">
          <div id="customDetailFormWrap1" class="global-custom-tab-content-wrap">
            <panel-form
              ref="tabName1Form"
              style="flex:1"
              table-name="DETAIL_ONE"
              class="strategy-panel"
              display="flex"
              :label-width="123"
              :no-resize="true"
              :readonly="detailFromData.objreadonly"
              :is-main-table="detailFromData.isMainTable"
              :default-data="detailFromData.data"
              @on-changeForm="onChangeDetailForm"
              @on-keydown="onKeydownForm"
            />
          </div>
          <div class="global-custom-table-wrap objectTable TableDetailCollection">
            <div class="detail-collection">
              <div class="detail-top">
                <ul class="detail-buttons">
                  <a id="actionMODIFY" @click="saveDetailHandle">【添加明细】</a>
                  <a id="actionDELETE" @click="deleteDetail">【删除明细】</a>
                </ul>
              </div>
            </div>
            <arkCommonTableByAgGrid
              height="400px"
              :columns="detailOneColumns"
              :data="currentDetailOneData"
              @on-selection-change="onSelectionChanged"
            />
          </div>
          <div class="pageContent">
            <Page
              size="small"
              show-elevator
              show-total
              show-sizer
              :current="onePageNum"
              :total="oneTotal"
              @on-change="commonChangePage"
              @on-page-size-change="commonChangeSzie" />
          </div>
        </TabPane>
      </Tabs>
    </div>
    <Spin fix v-if="isRequesting">
      <Icon type="ios-loading" size="18" style="animation: ani-demo-spin 1s linear infinite"></Icon>
      <div>加载中...</div>
    </Spin>
  </div>
</template>

<script>
const R3 = window.R3;
const { network } = R3;
import cloneDeep from 'lodash/cloneDeep';
// import debounce from 'lodash/debounce';
import { baseFormData, detailOneForm, simpleOneHeads } from "./form-db/addJitDistribution";

export default {
  components: {},
  filters: {},
  props: {
    componentData: {
      type: Object,
      default: ()=> {}
    },
  },
  data() {
    return {
      timer: null,
      isRequesting: false,
      isCopy: false,//是否是复制
      customizeId: -1,
      activeName: "detailOne",//备用
      panelFormData: {//基础信息form表单数据源
        objreadonly: false,
        isMainTable: true,
        data: {},
      },
      baseFormModel: {},//基础信息保存参数
      cacheFormModelStr: "",//复制新增时对比是否有有改动使用
      baseMustColumns: [],//基础信息必填列表
      // ----------基础信息end--------------
      detailFromData: {//JIT配货明细数据源
        objreadonly: false,
        isMainTable: true,
        data: detailOneForm,
      },
      detailOneFormModel: {},//JIT配货明细保存参数
      detailOneFormMustColumns: [],//JIT配货明细必填选项
      // detailOneColumns: detailOneTheads,
      detailOneColumns: simpleOneHeads,
      detailOneData: [],//临时总条数
      currentDetailOneData: [],//当前分页的数据
      checkedOneList: [],//当前选中行列表
      checkedOneIndexs: [],//当前选中行下标列表
      onePageNum: 1,
      onePageSize: 10,
      oneTotal: 0,
      // ---------JIT配货明细end-------------
    }
  },
  computed: {
    // baseData() { //店仓信息
    //   return this.$store.state.baseData
    // },
  },
  watch: {},
  created() {
    let currentId = this.$route.params.customizedModuleId;
    this.customizeId = currentId;
    this.mapSetFromModelFn({setType: 'base_info' });//初始化基础信息
    this.mapSetFromModelFn({setType: 'detail_one' });//初始化JTT配货明细
    if (currentId != "4172") {
      this.isCopy = true;
      // 如果时复制进来的
      this.loadCopyInfoFn();
    }
  },
  mounted() {},
  destroyed() {},
  methods: {
    // 明细页码变化，预留多个情况公用
    commonChangePage(num) {
      if (this.activeName == "detailOne") {
        this.onePageNum = num;
        this.updateOneList();
      }
    },
    // 明细当前页数量变化，预留多个情况公用
    commonChangeSzie(size) {
      if (this.activeName == "detailOne") {
        this.onePageSize = size;
        this.onePageNum = 1;
        this.updateOneList();
      }
    },
    // 复制新增时获取基础信息数据
    async loadCopyInfoFn() {
      if (this.isRequesting) return;
      const reqParam = {
        T_V_OMSJITDISTRIBUTION: {
          ID: this.customizeId,
        }
      }
      this.isRequesting = true;
      const res = await network.post('/p/cs/vip/distribution/detail', reqParam);
      const resultData = res.data || {};
      const { code, data } = resultData || {};
      if (code == 0) {
        this.customizeId = -1;// 复制新增保存时ID还是-1
        this.isRequesting = false;
        const {
          T_V_OMSJITDISTRIBUTION: baseInfo,
          T_OMSJITDISTRIBUTIONITEM: jitOneList
        } = data || {};
        this.setBaseInfoFn(baseInfo);
        this.detailOneData = jitOneList || [];
        this.updateOneList();
      } else {
        this.isRequesting = false;
      }
    },
    /**复制时基础信息填充
     * 输入框类型 3个--
     * 拣货单号 PICKNO,出仓单号 OUTSTORAGECODE,物流单号 WAYBILLNO
     * 外键类型 3个--
     * 下单店铺 ORDERSHOPID SHOPNAME
     * JIT仓库编码 JITWAREHOUSEID JITWAREHOUSENAME
     * 发货实体仓库 IESWAREHOUSEID WAREHOUSENAME
     * 下拉框类型 2个-- 值都是字符串
     * 配送方式 DELIVERY_METHOD,会员优先发货 PRIORITYDELIVERY(不用赋值)
     */
    setBaseInfoFn(obj) {
      if (obj && Object.keys(obj).length) {
        const copyBaseData = cloneDeep(this.panelFormData.data);
        const baseFormList = copyBaseData.addcolums[0].childs || [];
        if (baseFormList.length) {
          const showKeyMap = {
            "ORDERSHOPID": "SHOPNAME",
            "JITWAREHOUSEID": "JITWAREHOUSENAME",
            "IESWAREHOUSEID": "WAREHOUSENAME",
          }
          baseFormList.forEach(formItem => {
            const { colname:formKey, objdisplay } = formItem || {};
            // 排除会员优先
            if (formKey != "PRIORITYDELIVERY") {
              const lowerKey = formKey.toLowerCase();// 部分返回的key是小写,优先取大写
              let realValue = obj[formKey] || obj[lowerKey];
              // 注意部分下拉框的显示需要数字字符串
              if (typeof realValue === 'number') {
                realValue = String(realValue);
              }
              this.baseFormModel[formKey] = realValue || "";
              //  外键类型显示复制
              if (objdisplay && objdisplay == "object") {
                formItem["valuedata"] = obj[showKeyMap[formKey]] || "";
              } else {
                // 输入框和下拉框赋值
                formItem["valuedata"] = realValue || "";
              }
            }
          })
        }
        this.panelFormData.data = copyBaseData;
        this.cacheFormModelStr = JSON.stringify(cloneDeep(this.baseFormModel || {}));
      }
    },
    // 顶部保存
    async saveAllHandle() {
      if (this.isRequesting) return;
      // 必填项校验
      const emptyMustItem = this.checkMustCellFn({checkType: "all"});
      if (emptyMustItem) return;
      const params = {
        T_V_OMSJITDISTRIBUTION: {
          ...this.baseFormModel,
          ID: -1,
        }
      }
      if (this.detailOneData && this.detailOneData.length) {
        params["T_OMSJITDISTRIBUTIONITEM"] = this.detailOneData;
      }
      this.isRequesting = true;
      const res = await this.sameSaveHandle(params);
      const { code, message, data } = res || {};
      if (code == "0") {
        this.isRequesting = false;
        this.$Message.success(message);
        const { objId } = data || {};
        this.jumpPage({ detailItemId: objId });
      } else {
        this.isRequesting = false;
        this.$Message.error(message);
      }
    },
    filterOneDetailSaveItem() {
      const saveList = [];
      this.detailOneData.forEach((rowItem) => {
        const obj = {};
        Object.keys(rowItem).forEach(key => {
          obj[key] = rowItem[key].val || ""
        })
        saveList.push(obj);
      })
      return saveList;
    },
    // 删除明细
    deleteDetail() {
      if (!this.currentDetailOneData || !this.currentDetailOneData.length) return;
      if (!this.checkedOneIndexs.length) {
        this.$Message.warning("请选择要删除的列表!");
        return
      }
      this.detailOneData = this.detailOneData.filter(row => !this.checkedOneIndexs.includes(row.rowIndex));
      this.updateOneList()
    },
    // 配货明细保存
    saveDetailHandle() {
      // 必填项校验
      const emptyMustItem = this.checkMustCellFn({checkType: "detail"});
      if (emptyMustItem) return;
      this.detailOneFormModel.ID = -1;
      // const appendItem = {};
      // for (const key in this.detailOneFormModel) {
      //   appendItem[key] = { val: this.detailOneFormModel[key] || '' }
      // }
      this.detailOneData.push(this.detailOneFormModel);
      // 更新显示明细
      this.updateOneList();
      // 清空JIT配货明细条件
      this.mapSetFromModelFn({setType: 'detail_one' });
    },
    // 更新表格明细
    updateOneList() {
      this.detailOneData.forEach((row, index) => {
        row["showIndex"] = index + 1;//标记行号用于显示
        row["rowIndex"] = index;//标记行号用于删除
      })
      const startIndex = this.onePageSize * (this.onePageNum - 1);
      const endIndex = startIndex + this.onePageSize;
      this.currentDetailOneData = this.detailOneData.slice(startIndex, endIndex)
      this.oneTotal = this.detailOneData.length // 表格行总条数
      // 清空选中数据
      this.checkedOneIndexs = [];
      this.checkedOneList = [];
    },
    // 公用校验必填项
    checkMustCellFn(option) {
      let mustItem = null;
      const { checkType } = option || {};
      const allMust = {
        "all": this.baseMustColumns,
        "detail": this.detailOneFormMustColumns,
      }
      const allModels = {
        "all": this.baseFormModel,
        "detail": this.detailOneFormModel,
      }
      const tempModel = allModels[checkType] || {};
      const mustList = allMust[checkType] || [];
      if (mustList && mustList.length) {
        for (let i = 0; i < mustList.length; i++) {
          const { colname: paramKey } = mustList[i];
          let curVal = tempModel[paramKey] || '';
          // 如果当前必填选项没有值
          if (!curVal) {
            mustItem = mustList[i];
            break;
          }
        }
      }
      // 提示
      let errorTips = null;
      let elemId = null;
      if (mustItem && Object.keys(mustItem).length) {
        // 输入框就获取焦点
        const { colname, name: cellLabel } = mustItem;
        errorTips = `${cellLabel}不能为空!`;
        elemId = colname;
      }
      if (errorTips) {
        this.$Message.warning(errorTips);
        this.inputFocus({ areaType: checkType, elemId });//获取焦点
      }
      return mustItem;
    },
    // 根据不同类型初始化列合参数
    mapSetFromModelFn(option) {
      try {
        const { setType } = option || {};
        if (setType == 'base_info') {
          // 基础信息
          const baseForm = cloneDeep(baseFormData);
          const { addcolums:baseAddcolums = [] } = baseForm || {};
          const { childs:baseFormList = [] } = baseAddcolums[0] || {};
          const baseFormObj = {};
          const baseMustList = [];
          if (baseFormList && baseFormList.length) {
            baseFormList.forEach((item) => {
              const { colname, isnotnull } = item || {};
              // if (objdisplay && objdisplay == "object") {}
              if (isnotnull) {
                baseMustList.push(item);
              }
              baseFormObj[colname] = "";
            })
          }
          this.panelFormData.data = baseForm;
          this.baseFormModel = baseFormObj;
          this.baseMustColumns = baseMustList;
        } else if (setType == "detail_one") {
          // JIT配货明细
          const detailForm1 = cloneDeep(detailOneForm);
          const { addcolums:detailAddcolums = [] } = detailForm1 || {};
          const { childs:detailFormList = [] } = detailAddcolums[0] || {};
          const detailFormOneObj = {};
          const detailMustList1 = [];
          if (detailFormList && detailFormList.length) {
            detailFormList.forEach((item) => {
              const { colname, isnotnull } = item || {};
              if (isnotnull) {
                detailMustList1.push(item);
              }
              detailFormOneObj[colname] = "";
            })
          }
          this.detailFromData.data = detailForm1;
          this.detailOneFormModel = detailFormOneObj;
          this.detailOneFormMustColumns = detailMustList1;
          // this.getQuery({ tableName: "DELIVERY_METHOD" })//配送方式
          // this.getQuery({ tableName: "T_OMSREASONTYPE", fixed: { REFUNDTYPE: 2 } })//退换货原因
          // console.log(this.detailOneFormModel, 'this.detailOneFormModel')
          // console.log(this.detailOneFormMustColumns, 'this.detailOneFormMustColumns')
        }
        console.log(this.baseFormModel, 'this.baseFormModel')
        console.log(this.detailOneFormModel, 'this.detailOneFormModel')
      } catch (error) {
        console.log("init_custom_form_error_01", error);
      }
    },
    // 整个form任何一个变化时都会触发
    onChangeForm(valueInfo) {
      // console.log(valueInfo, 'wjf_01')
      const tempObj = { ...this.baseFormModel };
      Object.keys(valueInfo).forEach((key) => {
        tempObj[key] = valueInfo[key] || "";
      });
      this.baseFormModel = tempObj;
    },
    // 组件的keydown事件
    onKeydownForm(event) {
      const { keyCode } = event || {};
      if (keyCode == 13) {
        event.preventDefault();
        event.stopPropagation();
        this.saveDetailHandle();
      }
    },
    /**
     * valueInfo = {key:value}
     * items: {
     *  key: [{ID: "",Label: "",value:""}]
     * }
     */
    onChangeDetailForm(valueInfo, items) {
      // console.log(valueInfo, 'wjf_detail_01')
      // console.log(items, 'wjf_detail_items_01')
      const tempObj = { ...this.detailOneFormModel };
      Object.keys(valueInfo).forEach((key) => {
        tempObj[key] = valueInfo[key] || "";
        // 如果是条码时,追加显示字段明细使用
        if (key == "IESSKUID") {
          const curList = items[key] || [];
          tempObj["SKU"] = (curList[0] || {}).value;// 显示值
        }
      });
      this.detailOneFormModel = tempObj;
    },
    // 明细表格选中某项时触发
    onSelectionChanged(list) {
      this.checkedOneList = list || [];
      this.checkedOneIndexs = (list || []).map(item => item.rowIndex);
    },
    // 关闭和跳转到明细编辑
    jumpPage(option) {
      const { detailItemId } = option || {};
      const { fullPath } = this.$route;
      const {
        keepAliveModuleName,tableName
      } = this.$store.state.global.activeTab;
      this.$store.commit('global/tabCloseAppoint', {
        tableName,
        routeFullPath: fullPath,
        keepAliveModuleName,
        stopRouterPush: true,
      });
      this.timer = setTimeout(()=>{
        let backInfo = {
          type: 'S',
          tableName: 'T_V_OMSJITDISTRIBUTION',
          tableId: '10640',
          back: true
        }
        if (detailItemId) {
          backInfo = {
            type: 'S',
            url: `/SYSTEM/TABLE_DETAIL/V/T_V_OMSJITDISTRIBUTION/10640/${detailItemId}`
          }
        }
        R3.store.commit('global/tabOpen', backInfo);
        // 如果有基础信息改动或者明细改动没有保存就提示
        // const currentBaseFormStr = JSON.stringify(this.baseFormModel || {}) || "";
        // const isModifyBase = currentBaseFormStr !== this.cacheFormModelStr;
        // const currentOneDataStr = JSON.stringify(this.detailOneData || []) || "";
        // const isModifyOneList = currentOneDataStr !== this.cacheOneData;
        // if (isModifyBase || isModifyOneList) {
        //   // 有数据改动没有保存，确定关闭吗?
        // }
      }, 0)
    },
    realJumpPage(jumpOption) {
      R3.store.commit('global/tabOpen', jumpOption);
    },
    // 顶部保存接口同一个
    async sameSaveHandle(option = {}) {
      const res = await network.post('/p/cs/vip/distributionItem/create', option);
      const resultData = res.data || {};
      return resultData;
    },
    // async getQuery(option = {}) {
    //   if (this.isRequesting) return;
    //   this.isRequesting = true;
    //   const { tableName, fixed } = option || {};
    //   let reqParam={
    //     fixedcolumns: fixed || {},
    //     range: 1000,
    //     startindex: 0,
    //     table: tableName
    //   }
    //   const res = await network.post('/p/cs/list/query', reqParam);
    //   const { data } = res || {}
    //   // error时 data= {code: -1, data: null, message: "xxx"}
    //   // console.log(res, 'wjf_001')
    //   const { rows = [] } = data || {};
    //   if (rows && rows.length) {
    //     // 获取成功，赋值到指定选项下拉框列表
    //   }
    // },
    //输入框获取焦点
    inputFocus(option) {
      try {
        const { areaType, elemId } = option || {};
        const wrapDoms = {
          "all": document.getElementById("customBaseFormWrap"),
          "detail": document.getElementById("customDetailFormWrap1")
        }
        const areaWrap = wrapDoms[areaType] || null;
        this.$nextTick(()=> {
          if (areaWrap) {
            const inputParent = areaWrap.querySelector(`#${elemId}`);
            if (inputParent) {
              const inputElem = inputParent.getElementsByClassName("ark-input-default")[0] || null;
              if (inputElem) inputElem.focus();
            }
          }
        })
      } catch (error) {
        console.log(`focus-error`, error)
      }
    },
  }
}
</script>

<style lang="less" scoped>
</style>
