<template>
  <div style="margin-left: 8px">
    <section class="grid-wrap">
      <el-radio-group v-model="ruleType" @change="handleTabChange" class="header-radio">
        <el-radio-button label="2" :disabled="isPrivate" :class="{ 'btn-disabled': isPrivate }">企业</el-radio-button>
        <el-radio-button label="0" :disabled="isPublic" :class="{ 'btn-disabled': isPublic }">个人</el-radio-button>
        <el-radio-button label="1" :disabled="isPublic" :class="{ 'btn-disabled': isPublic }">商户</el-radio-button>
      </el-radio-group>
      <main>
        <section class="main-li">
          <p class="common-title">管户归属</p>
          <div class="title">
            <div style="display: flex">
              <el-button size="small" @click="onEditClick" type="primary" :disabled="newRulesOption.length === 0">
                {{ editMode ? '退出' : '编辑' }}
              </el-button>
              <el-button size="small" type="plain" :disabled="!editMode || rules.length === 0" @click="saveRule"> 保存
              </el-button>
            </div>
            <div>
              <el-button size="small" :disabled="editMode || newRulesOption.length === 0" @click="updateAll"
                type="primary">全量更新</el-button>
              <el-button size="small" :disabled="editMode || newRulesOption.length === 0" @click="updateNew"
                type="plain">增量更新</el-button>
            </div>
          </div>
          <ul>
            <li v-for="(rule, index) in rules" :key="rule.uid" class="table">
              <el-row :gutter="24">

                <el-col :span="16" class="vl"><span>类型：</span><span>{{ rule.name }}</span></el-col>
                <el-col :span="6" class="vr">
                  <el-button size="small" :disabled="!editMode || rules.length === 1" @click="removeRule(index)"
                    icon="el-icon-minus" circle>
                  </el-button>
                  <el-button size="small" :disabled="!editMode" @click="moveRule(index, -1)" icon="el-icon-top"
                    circle></el-button>
                  <el-button size="small" :disabled="!editMode" @click="moveRule(index, 1)" icon="el-icon-bottom"
                    circle></el-button>
                </el-col>
              </el-row>
            </li>
          </ul>
          <div class="operate-btn">
            <el-row :gutter="24">
              <el-col :span="16">
                <span>类型：</span>
                <el-select :disabled="!editMode" v-model="newRule" size="middle">
                  <el-option v-for="item in newRulesOption" :disabled="isChose(item, 'rules')" :key="item.uid"
                    :value="item.name">{{
                      item.name
                    }}</el-option>
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-button size="small" :disabled="!editMode" @click="handleAddRule" type="primary" icon="el-icon-plus"
                  circle></el-button>
              </el-col>
            </el-row>
          </div>
          <div class="radio">
            <p>更新频率：</p>
            <label class="radio-label"> <input type="radio" value="1" v-model="selectedOption" :disabled="!editMode" />
              按年更新 </label>
            <label class="radio-label"> <input type="radio" value="2" v-model="selectedOption" :disabled="!editMode" />
              按半年更新 </label>
            <label class="radio-label"> <input type="radio" value="3" v-model="selectedOption" :disabled="!editMode" />
              按季度更新 </label>
            <label class="radio-label"> <input type="radio" value="4" v-model="selectedOption" :disabled="!editMode" />
              按月更新 </label>
            <label class="radio-label"> <input type="radio" value="0" v-model="selectedOption" :disabled="!editMode" />
              手动更新 </label>
          </div>
        </section>
        <section class="main-li">
          <p class="common-title">地址归属</p>
          <div class="title">
            <div style="display: flex">
              <!-- editMode2 = !editMode2 -->
              <el-button size="small" :disabled="newRulesOption2.length === 0" @click="handledzEdit" type="primary">
                {{ editMode2 ? '退出' : '编辑' }}
              </el-button>
              <el-button size="small" :disabled="!editMode2 || rules2.length === 0" @click="saveRule2" type="plain"> 保存
              </el-button>
            </div>
            <div>
              <!-- :disabled="editMode2 || newRulesOption2.length === 0" -->
              <el-button size="small" @click="updateAll" disabled type="primary">全量更新</el-button>
              <el-button size="small" disabled @click="updateNew" type="plain">增量更新</el-button>
            </div>
          </div>
          <ul>
            <li v-for="(rule, index) in rules2" :key="rule.uid" class="table">
              <el-row :gutter="24">
                <el-col :span="8" class="vl"><span>来源：</span><span>{{ rule.addSource }}</span></el-col>
                <el-col :span="8" class="vl"><span>类型：</span><span>{{ rule.name }}</span></el-col>
                <el-col :span="6" class="vr">
                  <el-button size="small" :disabled="!editMode2 || rules2.length === 0" @click="removeRule2(index)"
                    icon="el-icon-minus" circle>
                  </el-button>
                  <el-button size="small" :disabled="!editMode2" @click="moveRule2(index, -1)" icon="el-icon-top"
                    circle></el-button>
                  <el-button size="small" :disabled="!editMode2" @click="moveRule2(index, 1)" icon="el-icon-bottom"
                    circle></el-button>
                </el-col>
              </el-row>
            </li>
          </ul>
          <div class="operate-btn">
            <el-row :gutter="24">
              <el-col :span="8">
                <span>来源：</span>
                <el-select :disabled="!editMode2" v-model="newType2" size="middle">
                  <el-option v-for="(item, index) in typeOption" :label="item.label" :value="item.value" :key="index"
                    :disabled="isChose(item, 'rules')"></el-option>
                </el-select>
              </el-col>
              <el-col :span="8">
                <span>类型：</span>
                <el-select :disabled="!editMode2" v-model="newRule2" size="middle" @change="handleNewRule2">
                  <el-option v-for="item in newRulesOption2" :key="item.uid"
                    :value="item.name">{{
                      item.name
                    }}</el-option>
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-button size="small" :disabled="!editMode2" @click="addRule2" type="primary" icon="el-icon-plus"
                  circle></el-button>
              </el-col>
            </el-row>
          </div>

          <div class="radio">
            <p>更新频率：</p>
            <label class="radio-label"> <input type="radio" value="1" v-model="selectedOption2" disabled />
              按年更新 </label>
            <label class="radio-label"> <input type="radio" value="2" v-model="selectedOption2" disabled />
              按半年更新 </label>
            <label class="radio-label"> <input type="radio" value="3" v-model="selectedOption2" disabled />
              按季度更新 </label>
            <label class="radio-label"> <input type="radio" value="4" v-model="selectedOption2" disabled />
              按月更新 </label>
            <label class="radio-label"> <input type="radio" value="0" v-model="selectedOption2" disabled />
              手动更新 </label>
          </div>
        </section>
      </main>
    </section>
  </div>
</template>
<script>
import { getRulesList, updateRule, addRule, updateRules, getParam, getAddressSource } from '@/api/grid/relationRules.js'
import { uid } from '@/utils'
import { Message } from 'element-ui'
import { isEmpty, omit, cloneDeep } from 'lodash'
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      rules: [],
      rules2: [],
      oriList: [],
      ruleType: '2',
      newType: '',
      newRule: '',
      newRule2: '',
      newType2: '',
      editMode: false,
      editMode2: false,
      selectedOption: '0',
      selectedOption2: '0',
      newId: '',
      typeOption: [],
      newRulesOption: [],
      newRulesOption2: [],
      paramData: {}
    }
  },
  watch: {
    isPrivate: {
      handler(val) {
        if (val) {
          this.ruleType = '0'
          this.getList()
        }
      },
      immediate: true
    }
  },
  computed: {
    ...mapGetters(['roles']),
    isPublic() {
      return this.roles.includes('headPublic')
    },
    isPrivate() {
      return this.roles.includes('headPrivate')
    }
  },
  created() {
    this.getList()
    this.getInitData()
    this.initAddressSource()
  },
  methods: {
    onEditClick() {
      this.editMode = !this.editMode
    },
    handledzEdit() {
      this.editMode2 = !this.editMode2
      this.getList()
    },
    isChose(row, str) {
      const listArr = this[str]?.filter((ot) => ot.name === row.name)
      return !isEmpty(listArr)
    },
    async getInitData() {
      const { data, code } = await getParam()
      if (code === 200) {
        this.paramData = data
        const dzArray = []
        const ghArray = []

        for (const key in data) {
          const item = {
            name: data[key],
            // enName: key,
            ruleNameId: key,
            idb: '',
            ruleType: this.ruleType,
            id: uid(),
            uid: uid(),
          }

          if (key?.includes(`${this.ruleType}_dz`)) {
            item.param = `${this.ruleType}_dz`
            item.updateCounts = this.selectedOption2
            dzArray.push(item)
          } else if (key?.includes(`${this.ruleType}_gh`)) {
            item.param = `${this.ruleType}_gh`
            item.updateCounts = this.selectedOption
            ghArray.push(item)
          }
        }
        this.newRulesOption = ghArray
        this.newRulesOption2 = dzArray
        console.log(this.newRulesOption2, 'this.newRulesOption2')
      }
    },
    initAddressSource() {
      this.typeOption = []
      getAddressSource().then(res => {
        if (res.code == 200) {
          for (const key in res.data) {
            const item = {
              value: key,
              label: res.data[key],
            }
            if (this.ruleType == '0') {
              if(item.value.charAt(0)=='0'){
                this.typeOption.push(item)
              }
            } else if (this.ruleType == '1') {
              if(item.value.charAt(0)==1){
                this.typeOption.push(item)
              }
            } else if (this.ruleType == '2') {
              if(item.value.charAt(0)=='2'){
                this.typeOption.push(item)
              }
            }
       
          }
        }
        console.log(this.typeOption, 'this.typeOption')
      })

    },
    handleNewRule2(){
      this.rules2.forEach(item=>{
        if(item.addSourceId ==this.newType2&&item.name ==this.newRule2 ){
          Message.warning('已有同样的数据，不可以添加')
          this.newRule2 = ''
          this.newType2 = ''
        }
      })
    },
    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)
    },
    getList() {
      getRulesList().then((response) => {
        this.oriList = response.data?.map((ot) => ({
          ...ot,
          uid: uid()
        }))
        
        this.rules = this.oriList?.filter((key) => key.ruleNameId?.startsWith(`${this.ruleType}_gh`) && key.ruleType === this.ruleType)?.sort(function (a, b) {
          return a.level - b.level
        })
        this.rules2 = this.oriList?.filter((key) => key.ruleNameId?.startsWith(`${this.ruleType}_dz`) && key.ruleType === this.ruleType)?.sort(function (a, b) {
          return a.level - b.level
        })
        console.log( this.rules2,' this.rules2 this.rules2')
        this.rules = this.getNorepeatArr(this.rules)
        // this.rules2 = this.getNorepeatArr(this.rules2)
      })
    },
    getTabData(arr, val) {
      return arr?.map((ot) => ({
        ...ot,
        ruleType: val
      }))
    },
    handleTabChange() {
      // 根据选中的选项更新表格数据
      this.editMode = false
      this.editMode2 = false
      this.rules = []
      this.rules2 = []
      this.getInitData()
      this.initAddressSource()
      this.getList()
    },
    handleAddRule() {
      if (this.newRule?.trim()) {
        const orilistArr = this.oriList?.filter((item) => item.ruleNameId?.startsWith(`${this.ruleType}_gh`))
        const temp = this.newRulesOption.find((item) => item.name === this.newRule)
        temp.id = !isEmpty(orilistArr) ? orilistArr[0].id : this.generateUUID()
        temp.deptId = !isEmpty(orilistArr) ? orilistArr[0].deptId : ''
        temp.uid = uid()
        this.rules.push(temp)
        this.newRule = ''
      }
    },
    addRule2() {
      if (this.newRule2?.trim()&&this.newType2?.trim()) {
        const orilistArr = this.oriList?.filter((item) => item.ruleNameId?.startsWith(`${this.ruleType}_dz`))
        const temp = this.newRulesOption2.find((item) => item.name === this.newRule2)
        const addressType = this.typeOption.find((item)=>item.value === this.newType2)
        temp.addSourceId = addressType.value
        temp.addSource = addressType.label
        temp.id = !isEmpty(orilistArr) ? orilistArr[0].id : this.generateUUID()
        temp.deptId = !isEmpty(orilistArr) ? orilistArr[0].deptId : ''
        temp.uid = uid()
        this.rules2.push({...temp})
    
        this.newRule2 = ''
        this.newType2 = ''
      }
    },
    removeRule(index) {
      this.rules.splice(index, 1)
    },
    removeRule2(index) {
      this.rules2.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()
        })
      }
    },
    moveRule2(index, direction) {
      const nextIndex = index + direction
      if (nextIndex >= 0 && nextIndex < this.rules2.length) {
        this.rules2[index].level = index + direction
        this.rules2[index + direction].level = index
        this.rules2.sort(function (a, b) {
          return a.level - b.level
        })
      }
    },
    updateAll() {
      updateRules({ op: 1 }).then((response) => {
        if (response.code === 200) {
          this.$message.success(response.data)
        }
      })
    },
    updateNew() {
      updateRules({ op: 2 }).then((response) => {
        if (response.code === 200) {
          this.$message.success(response.data)
        }
      })
    },
    findKeyByValue(obj, value) {
      const result = Object.entries(obj).find(([key, val]) => val === value)
      return result ? result[0] : null
    },
    saveRule() {
      const ghArr = this.oriList?.filter((item) => item.ruleNameId?.startsWith(`${this.ruleType}_gh`) && item.ruleType === this.ruleType)
      const constantId = this.generateUUID()
      const resultRules = cloneDeep(this.rules)?.map((item, idx) => {
        if (isEmpty(ghArr)) {
          return omit({
            ...item,
            idb: isEmpty(ghArr) ? '' : item.id,
            updateCounts: this.selectedOption,
            id: constantId,
            param: 'gh',
            level: idx
          }, ['uid', 'idb', 'deptId'])
        } else {
          return omit({
            ...item,
            idb: isEmpty(ghArr) ? '' : ghArr?.[0].id,
            updateCounts: this.selectedOption,
            id: constantId,
            param: 'gh',
            level: idx
          }, ['uid'])
        }
      })
      
      const apiUrl = isEmpty(ghArr) ? addRule : updateRule
      apiUrl(resultRules).then((response) => {
        if (response.code === 200) {
          this.$message.success(response.data)
          this.open = false
          this.editMode = false
          this.getList()
        } else {
          this.$message.error(response.msg || '操作失败')
        }
      })
    },
    saveRule2() {
      
      const dzArr = this.oriList?.filter((item) => item.ruleNameId?.startsWith(`${this.ruleType}_dz`) && item.ruleType === this.ruleType)
      const constantId = this.generateUUID()
      const resultRules = cloneDeep(this.rules2)?.map((item, idx) => {
        if (isEmpty(dzArr)) {
          return omit({
            ...item,
            idb: isEmpty(dzArr) ? '' : item.id,
            updateCounts: this.selectedOption,
            id: constantId,
            level: idx,
            param: 'dz',
          }, ['uid', 'idb', 'deptId'])
        } else {
          return omit({
            ...item,
            idb: isEmpty(dzArr) ? '' : dzArr?.[0].id,
            updateCounts: this.selectedOption,
            id: constantId,
            param: 'dz',
            level: idx
          }, ['uid'])
        }
      })
      const apiUrl = isEmpty(dzArr) ? addRule : updateRule
      apiUrl(resultRules).then((response) => {
        if (response.code === 200) {
          this.$message.success(response.data)
          this.open = false
          this.getList()
          this.editMode2 = false
        } else {
          this.$message.error(response.msg || '操作失败')
        }
      })
    },
    generateUUID() {
      return Date.now().toString(36) + Math.random().toString(36).substr(2, 5)
    }
  }
}
</script>
<style lang="scss" scoped>
button {
  margin-right: 5px;
}

::v-deep .el-select {
  width: 80%;
}

.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;

  ::v-deep .el-row {
    width: 100%;
  }

  .vl {
    flex: 1;
    padding: 0 12px;
    border: 1px solid #ebebeb;
    margin-left: 12px;

    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;

    .btn-disabled {
      ::v-deep .el-radio-button__inner {
        background-color: #e7e7e7;
      }
    }

    .el-radio-button {
      flex: 1;

      ::v-deep .el-radio-button__inner {
        width: 100%;
        border: none;
        font-weight: 400;
        letter-spacing: 0.44px;
        line-height: 25px;
        font-size: 16px;
        color: #666666;
        padding: 11px 0 12px 0;
      }

      ::v-deep .el-radio-button__orig-radio:checked+.el-radio-button__inner {
        background-color: #4886f8;
        font-weight: 400;
        color: #ffffff;
        border-bottom-left-radius: 0;
        border-bottom-right-radius: 0;
      }

      &:nth-child(2) {

        &::before,
        &::after {
          content: '';
          position: absolute;
          top: 50%;
          transform: translateY(-50%);
          height: 21px;
          width: 1px;
          background: #ebebeb;
          z-index: 1;
        }

        &::after {
          right: 1px;
        }
      }

      &.is-active {

        &::before,
        &::after {
          content: none;
        }
      }
    }
  }

  >main {
    padding: 30px;

    ul {
      padding: 0 10px;

      li {
        margin-bottom: 10px;

        &:last-child {
          margin-bottom: 0;
        }
      }
    }
  }

  .operate-btn {
    margin-top: 16px;
    padding: 0 10px;
  }

  .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>