<template>
  <div style="margin-left: 8px">
    <section class="grid-wrap">
      <el-radio-group v-model="selectedTab" @change="handleTabChange" class="header-radio">
        <el-radio-button label="3">企业</el-radio-button>
        <el-radio-button label="2">商户</el-radio-button>
        <el-radio-button label="1">个人</el-radio-button>
      </el-radio-group>
      <main>
        <section class="main-li" v-for="(item, index) in recordList" :key="`${item.title}${index}`">
          <!-- <section class="operate-area">
            <section class="vl">
              <el-button type="primary" size="small">编辑</el-button>
              <el-button type="plain" size="small">保存</el-button>
            </section>
            <section class="vr">
              <el-button type="primary" plain size="small">全部更新</el-button>
              <el-button type="primary" plain size="small">增量更新</el-button>
            </section>
          </section> -->
          <custom-rule :ruleObj="item" :ruleType="selectedTab" :oriList="oriList" :editMode.sync="editMode"></custom-rule>
        </section>
      </main>
    </section>
  </div>
</template>
<script>
import { getRulesList, updateRule, addRule, updateRules, getParam } from '@/api/grid/relationRules.js'
import { uid } from '@/utils'
import { isEmpty } from 'lodash'
import CustomRule from './components/custom-rule'

export default {
  components: { CustomRule },
  data() {
    return {
      selectedTab: '3',
      rules: [],
      oriList: [],
      newRule: '',
      editMode: false,
      selectedOption: '',
      newId: '1111',
      newRulesOption: [],
      recordList: []
    }
  },
  created() {
    this.getInit()
    this.selectedOption = '5'
  },
  methods: {
    async getInit() {
      const tasks = [
          getParam(),
          getRulesList()
      ]
      const [paramRes, listRes] = await Promise.all(tasks)
      const { data: paramData, code: paramCode } = paramRes
      const { data: listData, code: listCode } = listRes
     
      if (paramCode === 200 && listCode === 200) {
        this.oriList = listData?.map((ot) => ({
          ...ot,
          ruleNameId: this.findKeyByValue(paramData, ot.name),
          uid: uid()
        }))
        const dzArray = []
        const ghArray = []

        let dzLevel = 1
        let ghLevel = 1
        for (const key in paramData) {
          const item = {
            name: paramData[key],
            enName: key,
            ruleNameId: key,
            idb: '',
            updateCounts: 1,
            ruleType: this.selectedTab,
            id: uid(),
            uid: uid(),
          }

          if (key?.startsWith('dz_')) {
            item.level = dzLevel++
            item.param = 'dz_1'
            dzArray.push(item)
          } else if (key?.startsWith('gh_')) {
            item.level = ghLevel++
            item.param = 'gh_1'
            ghArray.push(item)
          }
        }
        this.recordList = [
          {
            selectArr: ghArray,
            title: '管户归属',
            rulesData: this.getRuleData(this.oriList, 'gh_'),
            isEdit: false
          },
          {
            selectArr: dzArray,
            title: '地址归属',
            rulesData: this.getRuleData(this.oriList, 'dz_'),
            isEdit: false
          }
        ]
        console.log(this.recordList, '======================>>>>')
      }
    },
    findKeyByValue(obj, value) {
      const result = Object.entries(obj).find(([key, val]) => val === value)
      return result ? result[0] : null
    },
    getRuleData(arr, str) {
        const resultArr = arr?.filter((key) => key.param?.startsWith(str) && key.ruleType === this.selectedTab)?.sort(function(a, b) {
          return a.level - b.level
        })
        return this.getNorepeatArr(resultArr)
    },
    getNorepeatArr(arr) {
      const uniqArr = arr?.reduce((acc, curr) => {
        const key = `${curr.ruleType}-${curr.name}`
        if(!acc[key]) {
          acc[key] = curr
        }
        return acc
      }, {})
      return Object.values(uniqArr)
    },
    handleTabChange() {
      // 根据选中的选项更新表格数据
      this.editMode = false
      this.getInit()
    },
    handleAddRule() {
      if (this.newRule?.trim()) {
        const orilistArr = this.oriList?.filter((item) => item.param?.startsWith('gh_'))
        const temp = this.newRulesOption.find((item) => item.name === this.newRule)
        temp.id = !isEmpty(orilistArr) ? orilistArr[0].id : this.newId
        temp.deptId = !isEmpty(orilistArr) ? orilistArr[0].deptId : ''
        temp.level = this.rules.length
        temp.uid = uid()
        this.rules.push(temp)
        this.newRule = ''
        console.log(temp,this.rules, this.oriList, '-=================================')
      }
    },
    removeRule(index) {
      this.rules.splice(index, 1)
    },
    moveRule(index, direction) {
      const nextIndex = index + direction
      if (nextIndex >= 0 && nextIndex < this.rules.length) {
        this.rules[index].level = index + direction
        this.rules[index + direction].level = index
        this.rules.forEach((item) => (item.idb = item.id))
        this.newId = this.generateUUID()
        this.rules.forEach((item) => (item.id = this.newId))
        this.rules.forEach((item) => (item.updateCounts = this.selectedOption))
        this.newRulesOption.forEach((item) => (item.id = this.newId))
        updateRule(this.rules).then((response) => {
          this.$modal.msgSuccess('修改成功')
          this.open = false
          this.getList()
        })
      }
    },
    updateAll() {
      updateRules({ op: 1 }).then((response) => {
        alert(response.msg)
      })
    },
    updateNew() {
      updateRules({ op: 2 }).then((response) => {
        alert(response.msg)
      })
    },
    saveRule() {
      const ghArr = this.oriList?.filter((item) => item.param?.startsWith('gh_') && item.ruleType === this.ruleType)
      this.rules = this.rules?.map((item) => {
        if (isEmpty(ghArr)) {
          return {
            ...item,
            idb: item.id,
            updateCounts: this.selectedOption,
            id: this.generateUUID()
          }
        } else {
          return {
            ...item,
            idb: ghArr?.[0].id,
            updateCounts: this.selectedOption,
            id: this.generateUUID()
          }
        }
      })
      // this.rules.forEach((item) => (item.idb = item.id))
      // console.log(this.rules, '111111111111111111111111111111111111111111')
      // this.newId = this.generateUUID()
      // this.rules.forEach((item) => (item.id = this.newId))
      // this.rules.forEach((item) => (item.updateCounts = this.selectedOption))
      // this.newRulesOption.forEach((item) => (item.id = this.newId))
      // return console.log(this.rules, '++++++++++++++++++++++++===============================>>>>>', this.oriList)
      const apiUrl = isEmpty(ghArr) ? addRule : updateRule
      apiUrl(this.rules).then((response) => {
        if (response.code === 200) {
          this.$message.success(response.data)
          this.open = false
          this.getList()
        } else {
          this.$message.error(response.msg || '操作失败')
        }
      })
      this.rules.forEach((item, index) => (item.level = index))
      this.editMode = false
    },
    generateUUID() {
      return Date.now().toString(36) + Math.random().toString(36).substr(2, 5)
    }
  }
}
</script>
<style lang="scss" scoped>
button {
  margin-right: 5px;
}
.title {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin: 24px 0;
  padding: 0 10px;
}
.updateAll-button {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  color: white;
  background-color: rgb(167, 38, 38);
  cursor: pointer;
}
.updateUp-button {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  color: white;
  background-color: rgb(207, 139, 13);
  cursor: pointer;
}
.updateAll-button:disabled {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  color: white;
  background-color: #ccc;
  cursor: not-allowed;
}
.updateUp-button:disabled {
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  color: white;
  background-color: #ccc;
  cursor: not-allowed;
}
.circle-button {
  border-radius: 50%;
  outline: none;
  background-color: #aaaaaa;
  color: white;
  background-color: rgb(20, 152, 211);
  border: none;
  height: 30px;
  width: 30px;
  cursor: pointer;
}
.circle-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
.circle-button-del {
  border-radius: 50%;
  outline: none;
  background-color: #aaaaaa;
  color: white;
  background-color: red;
  border: none;
  height: 30px;
  width: 30px;
  cursor: pointer;
}
.circle-button-del:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
.table {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .vl {
    flex: 1;
    padding: 0 12px;
    border: 1px solid #ebebeb;
    span {
      line-height: 32px;
      font-size: 14px;
      color: #3d3d3d;
    }
  }
  .vr {
    ::v-deep .el-button {
      margin: 0 0 0 15px;
      &.el-button--medium.is-circle {
        padding: 5px;
        border-color: #979797;
      }
      i {
        color: #979797;
      }
    }
  }
}
.rule {
  margin-left: 10px;
}
.radio {
  display: flex;
  align-items: center;
  margin-top: 16px;
}
.radio-label {
  margin-right: 5px;
  font-size: 10px;
  font-weight: 300;
  color: black;
}
.editable-button {
  background-color: rgb(20, 152, 211);
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
.editable-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
.grid-wrap {
  background-color: #ffffff;
  overflow: hidden;
  box-shadow: 0 3px 8px 0 #00000017;
  border-radius: 16px 16px 0 0;
  .grid-cnt {
    padding: 24px 30px;
  }
  .header-radio {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #ebebeb;
    .el-radio-button {
      flex: 1;
      ::v-deep .el-radio-button__inner {
        width: 100%;
        border: none;
        font-weight: 400;
        letter-spacing: 0.5px;
        line-height: 25px;
        font-size: 18px;
        color: #666666;
        padding: 11px 0 12px 0;
      }
      ::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
        background-color: #4886f8;
        font-weight: 600;
        color: #ffffff;
      }
    }
  }
  > main {
    padding: 30px;
    ul {
      padding: 0 10px;
      li {
        margin-bottom: 10px;
        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }

  .operate-area {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .main-li {
    padding-bottom: 36px;
    border-bottom: 1px dashed #dae0e6;
    margin-bottom: 32px;
  }
  .common-title {
    position: relative;
    color: #222222;
    line-height: 16px;
    font-weight: 600;
    font-size: 16px;
    padding-left: 10px;
    margin: 0;

    &::before {
      position: absolute;
      top: 50%;
      transform: translatey(-50%);
      left: 0;
      content: '';
      width: 3px;
      background-color: #4886f8;
      height: 16px;
      border-radius: 2px;
    }
  }
}
</style>