<template>
  <div class="common-wrap-elem" style="width: 760px;padding: 0 10px;" data-key='SET_SEND_AREA'>
    <div class="btn-wrap">
      <Button
        type="primary"
        size="small"
        @click="commonConfirmHandle">确定</Button>
      <Button
        type="primary"
        size="small"
        @click="cancelFn">取消</Button>
    </div>
    <div class="tree-wrap" style="min-height: 160px;max-height: 460px;overflow-y: auto;margin-top:10px">
      <!-- 异步渲染 -->
      <Tree :data="firstData" :load-data="loadChildren" show-checkbox @on-check-change="changeSelect"></Tree>
      <!-- 一次性渲染所有 -->
      <!-- <Tree :data="treeData" show-checkbox @on-check-change="changeSelect"></Tree> -->
    </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>
import cloneDeep from 'lodash/cloneDeep';
const R3 = window.R3;
const { network } = R3;
export default {
  components: {},
  filters: {},
  props: {
    /**
     * 组织-实体仓档案->设置配送区域 时fromtType没有值
     * 运营-促销活动->新增，编辑时 fromtType=omsActive
     */
    fromType: {
      type: String,
      default: ()=> ''
    },
    areaList: {
      type: Array,
      default: ()=> []
    }
  },
  data() {
    return {
      isRequesting: false,
      selectRow: [],
      originData: [],// 数据源所有省市区，一维数组
      firstData: [],
      asyncChildrenObj:{},// 假装异步加载的数据源，带选中状态的
      treeData: [
        {
          "ID":1,
          "PARENTID":0,
          "PARPARENTID":null,
          "REGIONNAME":"中国",
          "REGTYPE":1,
          loading: false,
          title: "中国",
          children: [],
        }
      ],
      checkedIds: [],// 接口查询上次的选中ID列表, fromType有值时不从接口获取
      checkedList: [],
      saveDict: {}, // { 420100: [], 350300: []}
      // 促销活动使用的参数
      backInfo: {
        RECEIVPROVINCE: [],
        RECEIVCITY: [],
        RECEIVAREA: [],
      }
    }
  },
  computed: {
    //没跳转前选中的条数只有一个
    selectedDetailList() {
      return this.$store.state.customize.returnExchangeSelectDetail;
    }
  },
  watch: {},
  created() {
    if (this.fromType === 'omsActive') {
      // 促销活动新增和编辑时
      console.log(this.areaList, 'this.areaList');
      this.loadAllHandle();
    } else {
      this.initFn()
    }
  },
  mounted() {},
  destroyed() {},
  methods: {
    changeSelect(list, item) {
      // console.log(JSON.stringify(list), 'aaa')
      // console.log(list, 'aaa')
      this.checkedList = list;
      if (list && list.length && !this.fromType) {
        const checkNum = list.length;
        const chinaItem = list[0] || {};
        const { ID, REGTYPE } = chinaItem || {};
        // 实体仓时入参格式-------
        const provinceByCity = {};
        const isFirstOpenCheckChina = ((checkNum === 1) && (ID === 1) && (REGTYPE === 1)) ? true : false;
        let cityList = list.filter(item => item.PARPARENTID === 1) || [];
        // 如果是首次打开没展开时选中中国
        if (isFirstOpenCheckChina) {
          cityList = this.originData.filter(item => item.PARPARENTID === 1) || [];
        }
        if (cityList.length) {
          cityList.forEach(item => {
            const { PARENTID } = item || {};
            if (PARENTID && (PARENTID != 1)) {
              // 市
              if (!provinceByCity[PARENTID]) {
                provinceByCity[PARENTID] = [item];//备用
              } else {
                provinceByCity[PARENTID].push(item);
              }
            }
          })
        }
        this.saveDict = provinceByCity;
        // console.log(cityList, 'cityList');
        // console.log(this.saveDict, 'this.saveDict1');
      }
    },
    // 假装异步渲染子列表--nouse
    loadChildren(item, callback) {
      const { ID } = item || {};
      let childData = [];
      if (ID) {
        childData = JSON.parse(JSON.stringify(this.asyncChildrenObj[ID] || []));
      }
      callback(childData);
    },
    // 匹配列表页选中行
    initFn() {
      try {
        let modelName = R3.getModuleName();
        // let idarray = this.$store.state[modelName].buttons.selectIdArr;
        let selectArray = this.$store.state[modelName].buttons.selectArr;
        this.selectRow = selectArray;
        this.getQuery()
      } catch (error) {
        console.log(`init_tree_error`, error)
      }
    },
    // 获取选中行的选中的省市区
    async getQuery() {
      if (this.isRequesting) return;
      this.isRequesting = true;
      // const { tableName, fixed } = option || {};
      const idVal = this.selectRow[0].ID.val || '';
      let reqParam={
        "table": "T_IESWAHOSDELIVERYREGION",
        "startindex": 0,
        "range": 5000,
        "fixedcolumns": {
          "IESWarehouseId": [`=${idVal}`]
        },
        "fkdrplist": {
          "searchcols": [
            "CITYID"
          ],
          "orderby": [
            {
              "asc": true,
              "column": "ID"
            }
          ]
        },
        "isdroplistsearch": true
      }
      const res = await network.post('/p/cs/list/query', reqParam);
      const { data } = res || {}
      // error时 data= {code: -1, data: null, message: "xxx"}
      const { rows = [] } = data || {};
      if (rows && rows.length) {
        this.isRequesting = false;
        // 获取成功，赋值到指定选项下拉框列表
        this.checkedIds = rows.map(item => item.CITYID.refobjid) || [];
      } else {
        this.isRequesting = false;
      }
      this.loadAllHandle()
    },
    // 获取所有省市区数据源
    async loadAllHandle() {
      if (this.isRequesting) return;
      this.isRequesting = true;
      // const param = {}
      const startReqTime = performance.now();
      const res = await network.post('/p/cs/region/getRegionData', '');
      const resData = res.data || {};
      const { code, data, message } = resData;
      if (code == 0) {
        const endReqTime = performance.now();
        const duration = endReqTime - startReqTime;
        const reqTimeDiff = `请求时间:${duration.toFixed(3)}ms`;
        console.log(reqTimeDiff);
        this.isRequesting = false;
        // this.originData = data;//cloneDeep(data) || [];
        // console.log(JSON.stringify(this.originData), 'originData_01');
        if (data && data.length) {
          data.forEach(item => {
              const { PARPARENTID,PARENTID,ID } = item || {};
              item.PARPARENTID = Number(PARPARENTID);  
              item.PARENTID = Number(PARENTID);
              item.ID = Number(ID);        
          })
          this.originData = this.mapSetCheckedFn(data);
          const allTreeData = this.buildTree(this.originData);
          // console.log(JSON.stringify(allTreeData), 'allTreeData_01');
          // 设置是否选中
          this.treeData = this.processAreaList(allTreeData, this.checkedIds);
          const firstInfo = JSON.parse(JSON.stringify(this.treeData[0]));
          firstInfo.children = [];// 懒加载时该子元素清除
          this.firstData = [firstInfo];
          // 逻辑计算时间
          const endCalcTime = performance.now();
          const end = endCalcTime - endReqTime;
          const calcTimeDiff = `计算时间:${end.toFixed(3)}ms`;
          console.log(calcTimeDiff);
          const areaTime = { reqTimeDiff, calcTimeDiff }
          sessionStorage.setItem("AREA_TIME", JSON.stringify(areaTime));
          console.log(this.treeData, 'this.treeData_01');
          // console.log(this.asyncChildrenObj, 'this.asyncChildrenObj');
        }
      } else {
        this.isRequesting = false;
        this.$store.commit("messageDialog", {
          message,
          show: true,
          callback: ()=> {}
        });
      }
    },
    processAreaList(areaList, checkid) {
      // 递归函数：处理当前节点及其子节点
      const hasChildObj = {};
      function processNode(node, parentIdMap) {
        // 如果当前节点的ID在checkid中，设置selected为true
        if (checkid.includes(node.ID)) {
          // 向上设置父节点的selected为true
          let currentParentId = node.PARENTID;
          while (currentParentId !== null) {
            const parent = parentIdMap[currentParentId];
            if (parent) {
              parent.indeterminate = true;
              currentParentId = parent.PARENTID;
            } else {
              break;
            }
          }
        }
        // 如果当前节点有子节点，递归处理子节点
        if (node.children && node.children.length) {
          // let allChildrenChecked = true; // 用于判断所有子节点是否都被checked
          let checkCount = 0;
          node.children.forEach((child) => {
            processNode(child, parentIdMap);
            if (child.checked) {
              // allChildrenChecked = false;
              checkCount += 1;
            }
          });
          // 如果所有子节点都被checked，设置当前节点的selected为false，checked为true
          if (checkCount === node.children.length) {
            node.indeterminate = false;
            node.checked = true;
          }
        }
        if (node.REGTYPE < 4 && (node.children && node.children.length)) {
          hasChildObj[node.ID] = node.children || [];
        }
      }
      // 创建一个父节点ID映射表，方便快速查找父节点
      const parentIdMap = {};
      areaList.forEach((rootNode) => {
        const stack = [rootNode];
        while (stack.length > 0) {
          const current = stack.pop();
          parentIdMap[current.ID] = current;
          if (current.children) {
            stack.push(...current.children);
          }
        }
      });
      // 遍历areaList，处理每个节点
      areaList.forEach((rootNode) => {
        processNode(rootNode, parentIdMap);
      });
      this.asyncChildrenObj = hasChildObj;
      // console.log(parentIdMap, 'parentIdMap');
      console.log(hasChildObj, 'hasChildObj');
      return areaList;
    },
    /**
     * 先在数据源上设置checked属性
     * 实体仓档案时 都是城市ID
     * 促销编辑时：省ID，市ID，区域ID
     */
    mapSetCheckedFn(originList) {
      if (this.fromType === 'omsActive') {
        if (this.areaList.length) {
          const provIdArr = [];
          const cityIdArr = [];
          const areaIdArr = [];
          const selectedAreaIds = [];
          this.areaList.forEach(item => {
            const { RECEIVPROVINCE, RECEIVCITY, RECEIVAREA } = item;
            if (RECEIVPROVINCE && !RECEIVCITY && !RECEIVAREA) {
              provIdArr.push(Number(RECEIVPROVINCE));
            }
            if (RECEIVPROVINCE && RECEIVCITY && !RECEIVAREA) {
              cityIdArr.push(Number(RECEIVCITY));
            }
            if (RECEIVPROVINCE && RECEIVCITY && RECEIVAREA) {
              areaIdArr.push(Number(RECEIVAREA));
            }
          })
          // console.log(JSON.stringify(provIdArr), 'provIdArr_01')
          // 过滤所有选中区域ID
          originList.forEach(area => {
            const { ID, PARENTID, PARPARENTID } = area;
            if ((provIdArr.indexOf(PARPARENTID) >= 0) || (provIdArr.indexOf(ID) >= 0)) {
              area.checked = true;
            }
            if ((cityIdArr.indexOf(PARENTID) >= 0) || (cityIdArr.indexOf(ID) >= 0)) {
              area.checked = true;
            }
            if ((areaIdArr.indexOf(ID) >= 0)) {
              area.checked = true;
            }
          })
          this.checkedIds = [...provIdArr, ...cityIdArr, ...areaIdArr];
          console.log(this.checkedIds, 'selectedAreaIds');
        }
      }
      if (!this.fromType) {
        // 来自实体仓档案
        if (this.checkedIds.length) {
          this.checkedIds.forEach(tempId => {
            originList.forEach(item => {
              const { ID, PARENTID, PARPARENTID } = item;
              if ((ID === tempId) || (PARENTID === tempId) || (PARPARENTID === tempId)) {
                item.checked = true;
              }
            })
          })
        }
      }
      return originList;
    },
    // 构建树形结构的辅助函数
    buildTree(array, parentId = 0) {
      const tree = [];
      const treeObj = {};
      const children = array.filter(item => item.PARENTID === parentId);
      for (const child of children) {
        const node = {
          ...child,
          loading: false,
          title: child.REGIONNAME,
          // checked: this.checkedIds.includes(child.ID),
          checked: child.checked || false,// 选项是否选中
          children: this.buildTree(array, child.ID),
          indeterminate: false, // 子元素是否有选中的
        };
        // 实体仓档案页面，【设置配送区域】原本不能单纯选区，这里直接禁用
        if (this.fromType === '' || !this.fromType) {
          node.disabled = (child.PARPARENTID && ![0, 1].includes(child.PARPARENTID)) ? true : false;
        }
        tree.push(node);
      }
      return tree;
    },
    commonConfirmHandle() {
      if (this.fromType === 'omsActive') {
        // 促销活动新增和编辑时
        const backObj = this.mapForBack(this.checkedList);
        this.$emit('callBack', { isShow: false, allInfo: backObj });
      } else {
        this.confirmFn();
      }
    },
    /**
     * 促销活动使用
     * [{RECEIVPROVINCE: 350000, RECEIVCITY: '', RECEIVAREA: '' },
     * { RECEIVPROVINCE: 420000, RECEIVCITY: 420100, RECEIVAREA: '' },
     * { RECEIVPROVINCE: 360000, RECEIVCITY: 360100, RECEIVAREA: 360102 }]
     */
    mapForBack(checkedArr) {
      const backInfo = {};
      if (checkedArr.length) {
        let isOnlyCheckChina = false;
        const onlyItem = checkedArr[0];
        const { ID, REGTYPE } = onlyItem;
        const otherList = [];
        const provinceList = [];
        const provinceIds = [];
        const cityList = [];
        const cityIds = [];
        if (checkedArr.length === 1 && ID === 1 && REGTYPE === 1) {
          // 首次打开只选择了中国
          this.originData.forEach(item => {
            const { REGTYPE } = item;
            if (REGTYPE === 2) {
              provinceList.push(item);
            }
          });
        } else {
          checkedArr.forEach(checkItem => {
            const { ID, PARENTID, PARPARENTID } = checkItem || {};
            if (PARENTID === 1 && PARPARENTID === 0) {
              if (provinceIds.indexOf(ID) < 0) {
                provinceIds.push(ID);
                provinceList.push(checkItem);
              }
            }
          })
          checkedArr.forEach(checkItem => {
            const { ID, PARENTID, PARPARENTID } = checkItem || {};
            if (PARENTID !== 1 && PARPARENTID === 1) {
              if (provinceIds.indexOf(PARENTID) < 0) {
                if (cityIds.indexOf(ID) < 0) {
                  cityIds.push(ID);
                  cityList.push(checkItem);
                }
              }
            }
          })
          checkedArr.forEach(checkItem => {
            const { ID, PARENTID, PARPARENTID } = checkItem || {};
            if (PARENTID !== 1 && (PARPARENTID !== 0 && PARPARENTID !== 1)) {
              if ((provinceIds.indexOf(PARPARENTID) < 0) && (cityIds.indexOf(PARENTID) < 0)) {
                otherList.push(checkItem)
              }
            }
          })
        }
        backInfo.RECEIVPROVINCE = provinceList;
        backInfo.RECEIVCITY = cityList;
        backInfo.RECEIVAREA = otherList;
      }
      // console.log(provinceIds, cityIds, 'provinceIds')
      // console.log(otherList, 'otherList')
      console.log(backInfo, 'backInfo_01')
      return backInfo;
    },
    async confirmFn() {
      // const dictIds = this.mapSetForSave();
      const dictIds = this.mapSetForWarehouse();
      if (this.isRequesting || !dictIds || !dictIds.length) {
        this.$Message.warning('请选择一个节点!');
        return;
      }
      const selectRowId = this.selectRow[0].ID.val || '';
      const reqParam = {
        "ids": [selectRowId],
        "tableName": "T_IESWAREHOUSE",
        "actionName": "T_IESWAREHOUSE_确认设置配送区域",
        "param": {
          "DATA": [
            {
              "IESWAREHOUSEID": selectRowId,
              "FORMATREGION": dictIds.join(',')
            }
          ]
        },
        "isContainsParam": true
      }
      this.isRequesting = true;
      const res = await network.post('/p/cs/exeAction', reqParam);
      const resData = res.data || {}
      const { code, message } = resData || {}
      if (code == 0) {
        this.isRequesting = false;
        this.$Message.success(message);
        this.cancelFn();
      } else {
        this.isRequesting = false;
        this.$Message.error(message);
      }
    },
    mapSetForWarehouse() {
      const endIds = []; // 省|市1-市2-.. ['420000|420100-420300-..']
      for (const provIdKey in this.saveDict) {
        const cityArr = this.saveDict[provIdKey] || [];
        if (cityArr && cityArr.length) {
          const cityIdArr = cityArr.map(item => item.ID) || [];
          const cityIdStr = cityIdArr.join('-');
          endIds.push(`${provIdKey}|${cityIdStr}`);
        }
      }
      return endIds;
    },
    // 旧版实体仓--暂时作废
    mapSetForSave() {
      const endIds = []; // 市|区1-区2-区3 ['420100|420102-420103-420104']
      if (this.checkedList.length) {
        this.checkedList.forEach(checkItem => {
          const { PARENTID, ID } = checkItem || {};
          const dictArr = this.saveDict[PARENTID] || null;
          if (dictArr && !dictArr.includes(ID)) {
            this.saveDict[PARENTID].push(ID)
          }
        })
      }
      for (const cityId in this.saveDict) {
        const areaIds = this.saveDict[cityId] || [];
        if (areaIds && areaIds.length) {
          const areaIdStr = areaIds.join('-');
          endIds.push(`${cityId}|${areaIdStr}`)
        }
      }
      return endIds;
    },
    cancelFn() {
      // 促销活动新增和编辑时
      if (this.fromType === 'omsActive') {
        this.$emit('callBack', { isShow: false });
      } else {
        this.$emit('closeActionDialog', true);
      }
    },
    //输入框获取焦点
    inputFocus(id) {
      try {
        this.$nextTick(()=> {
          const elem = document.getElementById(id);
          if (elem) elem.focus();
        })
      } catch (error) {
        console.log(`focus-error`, error)
      }
    },
  }
}
</script>

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