<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="90"
        :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="物理调整单扫描明细" 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="120"
              :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/AddsadJuststock";

export default {
  components: {},
  filters: {},
  provide() {
    return {
      moduleComponentName: this.moduleComponentName
    }
  },
  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,
      tableName:'',
      moduleComponentName:'C.ADDSADJUSTSTOCK'

      // ---------JIT配货明细end-------------
    }
  },
  computed: {
    // baseData() { //店仓信息
    //   return this.$store.state.baseData
    // },
  },
  watch: {},
  created() {
    let currentId = this.$route.params.customizedModuleId;
    this.customizeId = currentId;
    this.tableName = this.$route.params.customizedModuleName;
    this.mapSetFromModelFn({setType: 'base_info' });//初始化基础信息
    this.mapSetFromModelFn({setType: 'detail_one' });//初始化明细
    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_WMSADJUSTSTOCK: {
          ID: this.customizeId,
        }
      }
      this.isRequesting = true;
      const res = await network.post('/p/cs/adjuststock/detail', reqParam);
      const resultData = res.data || {};
      const { code, data } = resultData || {};
      if (code == 0) {
        this.customizeId = -1;// 复制新增保存时ID还是-1
        this.isRequesting = false;
        const {
          T_V_WMSADJUSTSTOCK: baseInfo,
          T_WMSADJUSTQRCODE: jitOneList
        } = data || {};
        this.setBaseInfoFn(baseInfo);
        this.detailOneData = jitOneList || [];
        this.updateOneList();
      } else {
        this.isRequesting = false;
      }
    },
    /**复制时基础信息填充
     * 输入框类型 3个--
      仓库 STORENAME IESSTOREID、调整类型 ADJUSTTYPENAME ADJUSTTYPE、备注  --REMARK 、物理调整单扫描明细（原单所有条码及数量）    
      
     */
    setBaseInfoFn(obj) {
      if (obj && Object.keys(obj).length) {
        const copyBaseData = cloneDeep(this.panelFormData.data);
        const baseFormList = copyBaseData.addcolums[1].childs || [];
        if (baseFormList.length) {
          const showKeyMap = {
            "IESSTOREID": {
              label:obj.STORENAME,
              ID:obj.IESSTOREID,
            },
            "ADJUSTTYPE": {
              label:obj.ADJUSTTYPENAME,
              ID:obj.ADJUSTTYP,
            },
            "REMARK": obj.REMARK,
          }
          baseFormList.forEach(formItem => {
            const { colname:formKey, objdisplay } = formItem || {};
            const lowerKey = formKey.toLowerCase();// 部分返回的key是小写,优先取大写
              let realValue = obj[formKey] || obj[lowerKey];
              // 注意部分下拉框的显示需要数字字符串
              if (typeof realValue === 'number') {
                realValue = String(realValue);
              }
            if(showKeyMap[formKey]){
              this.baseFormModel[formKey] = realValue || "";
              // 外键类型显示复制
              if (objdisplay && objdisplay == "object") {
                formItem["valuedata"] = showKeyMap[formKey].label || "";
                formItem.refobjid = showKeyMap[formKey].ID ||''
              } else {
                // 输入框和下拉框赋值
                formItem["valuedata"] = realValue || "";
              }
              }
          })
        }
        this.panelFormData.data = copyBaseData;
        this.cacheFormModelStr = JSON.stringify(cloneDeep(this.baseFormModel || {}));
      }
    },
    // 顶部保存
    async saveAllHandle() {
      if (this.isRequesting) return;
      // 必填项校验
      const validationFailed = this.checkMustCellFn({checkType: "all"});
      if (!validationFailed) {
        return; // 校验失败直接返回，不执行保存
      }
      
      // 处理明细数据
      let processedDetailData = [];
      if (this.detailOneData && this.detailOneData.length) {
        // 对明细数据进行处理
        processedDetailData = this.detailOneData.map(item => {
          const newItem = { ...item };
          // 设置ID为-1
          newItem.ID = -1;
          
          // 如果没有SKU_QRCODE，则使用V_T_IESSKU_ID或QRCODE值
          if (!newItem.SKU_QRCODE) {
            newItem.SKU_QRCODE = newItem.QRCODE || newItem.sku || '';
          }
          
          return newItem;
        });
      }
      
      const params = {
        T_V_WMSADJUSTSTOCK: {
          ...this.baseFormModel,
          ID: -1,
        }
      }
      if (processedDetailData.length > 0) {
        params["T_WMSADJUSTQRCODE"] = processedDetailData;
      }
      params.type = 1
      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() {
      // 使用 tabName1Form 的校验
      if (!this.$refs.tabName1Form) {
        this.$Message.warning('表单引用获取失败');
        return;
      }
      
      let validate = this.$refs.tabName1Form.validate();
      if (validate.length > 0) {
        this.$Message.warning(validate[0].tip);
        let dom = document.querySelector(`#${validate[0].colname}`);
        if (dom) {
          let Input = dom.querySelector('input') || dom.querySelector('textarea');
          if (Input) {
            Input.focus();
          }
        }
        return;
      }
      
      // 获取表单数据
      const formData = this.$refs.tabName1Form.formData;
      console.log('Form data:', formData);
      
      // 添加行序号
      const nextIndex = this.detailOneData.length + 1;
      
      // 创建新的明细项
      const newDetailItem = { ...formData };
      newDetailItem.ID = -1; // 新增项ID为-1
      newDetailItem.showIndex = nextIndex; // 显示序号
      newDetailItem.rowIndex = this.detailOneData.length; // 行索引
      
      console.log('Adding new detail item:', newDetailItem);
      
      // 添加到明细列表
      this.detailOneData.push(newDetailItem);
      
      // 更新显示明细
      this.updateOneList();
      
      // 清空明细表单
      if (this.$refs.tabName1Form.reset) {
        this.$refs.tabName1Form.reset();
      } else {
        this.mapSetFromModelFn({setType: 'detail_one'});
      }
      
      this.$Message.success('明细添加成功');
    },
    // 更新表格明细
    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 validate = this.$refs.objform.validate();
         if(validate.length > 0){
            this.$Message.warning(validate[0].tip);
            let dom = document.querySelector(`#${validate[0].colname}`);
            if(dom){
              let Input = dom.querySelector('input') || dom.querySelector('textarea');
              if(Input){
                  Input.focus();
              }
            }
            return false;
        }
            return true;
    },
    // 根据不同类型初始化列合参数
    mapSetFromModelFn(option) {
      try {
        const { setType } = option || {};
        if (setType == 'base_info') {
          // 基础信息
          const baseForm = cloneDeep(baseFormData);
          const { addcolums:baseAddcolums = [] } = baseForm || {};
          // 获取基础信息表单和必填项
          const { childs:baseFormList = [] } = baseAddcolums[1] || {};
          const { childs:baseMustList = [] } = baseAddcolums[1] || {};
          const baseFormObj = {};
          
          if (baseFormList && baseFormList.length) {
            baseFormList.forEach((item) => {
              const { 
                colname, 
                isnotnull, 
                valuedata, 
                defval,
                display 
              } = item || {};
              // 优先使用 valuedata 作为默认值
              if(defval === 0 && display ==='OBJ_DATENUMBER'){
                const currentDate = new Date();
                const formattedDate = `${currentDate.getFullYear()}${String(currentDate.getMonth() + 1).padStart(2, '0')}${String(currentDate.getDate()).padStart(2, '0')}`;
                baseFormObj[colname] = Number(formattedDate);
                item.defval = formattedDate
                item.valuedata = formattedDate;
              }else{
                baseFormObj[colname] = valuedata || defval || "";
                item.valuedata = valuedata || defval || "";
              }
            })
          }
          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, valuedata } = item || {};
              if (isnotnull) {
                detailMustList1.push(item);
              }
              detailFormOneObj[colname] = valuedata || "";
              item.valuedata = valuedata || "";
            })
          }
          this.detailFromData.data = detailForm1;
          this.detailOneFormModel = detailFormOneObj;
          this.detailOneFormMustColumns = detailMustList1;
        }
      } catch (error) {
        console.log("init_custom_form_error_01", error);
      }
    },
    // 整个form任何一个变化时都会触发
    onChangeForm(valueInfo) {
      const tempObj = { ...this.baseFormModel };
      Object.keys(valueInfo).forEach((key) => {
        // 只有当新值不为空时才更新，保留原有的值
        if (valueInfo[key] !== undefined && valueInfo[key] !== null && valueInfo[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_WMSADJUSTSTOCK',
          tableId: '10923',
          back: true
        }
        if (detailItemId) {
          backInfo = {
            type: 'S',
            url: `/SYSTEM/TABLE_DETAIL/V/T_V_WMSADJUSTSTOCK/10923/${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/drp/wmsadjuststockSave', 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 || {};
        // 记录调试信息
        console.log('inputFocus:', areaType, elemId);
        const wrapDoms = {
          "all": document.getElementById("customBaseFormWrap"),
          "detail": document.getElementById("customDetailFormWrap1")
        }
        const areaWrap = wrapDoms[areaType] || null;
        console.log('areaWrap:', areaWrap);
        
        this.$nextTick(()=> {
          if (areaWrap) {
            // 使用更通用的选择器查找元素
            let inputParent = areaWrap.querySelector(`#${elemId}`);
            console.log('inputParent by id:', inputParent);
            
            // 如果通过ID没找到，尝试通过其他方式查找
            if (!inputParent) {
              inputParent = areaWrap.querySelector(`[name="${elemId}"]`);
              console.log('inputParent by name:', inputParent);
            }
            
            if (!inputParent) {
              inputParent = areaWrap.querySelector(`[colname="${elemId}"]`);
              console.log('inputParent by colname:', inputParent);
            }
            
            if (inputParent) {
              // 尝试查找各种可能的输入元素
              const inputElem = inputParent.querySelector('input') 
                || inputParent.querySelector('select') 
                || inputParent.querySelector('.ark-input-default')
                || inputParent.querySelector('.ark-formitem-control-wrapper');
              
              console.log('inputElem:', inputElem);
              if (inputElem) {
                inputElem.focus();
                console.log('focus set on element');
              }
            } else {
              console.log(`未找到元素: ${elemId}`);
            }
          } else {
            console.log(`未找到区域: ${areaType}`);
          }
        })
      } catch (error) {
        console.log(`focus-error`, error)
      }
    },
  }
}
</script>

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