<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="5vh"
    width="900px"
    :close-on-click-modal="false"
    :visible.sync="showModelThis"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    @close="closeModel"
  >
    <el-card>
      <el-row :gutter="10">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          status-icon
          :rules="rulesThis"
          label-width="80px"
          class="demo-ruleForm"
        >
          <el-col :span="12">
            <el-form-item label="角色名称" prop="role_name">
              <el-input
                v-model="ruleForm.role_name"
                :disabled="isDetail"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色等级" prop="level">
              <el-select
                v-model="ruleForm.level"
                filterable
                :disabled="isDetail"
                placeholder="请选择角色等级"
                style="width: 100%"
              >
                <el-option
                  v-for="item in roleLevel"
                  :key="'ruleid' + item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <div class="quanxian-main">
            <div class="quanxian-title">
              <span style="color: #ff8888">*</span><span
                style="
                  font-size: 14px;
                  color: #606266;
                  line-height: 40px;
                  padding: 0 12px 0 0;
                  font-weight: 700;
                "
              >功能权限</span>
            </div>
            <div class="quanxian">
              <el-col :span="24">
                <div />
                <el-row
                  v-for="(item, index) in actionList"
                  :key="'menu' + item.id + index"
                >
                  <el-col v-if="item.child && item.child.length > 0" :span="24">
                    <el-row
                      v-for="(subItem, subIndex) in item.child"
                      :key="'yemian' + subItem.id + subIndex"
                    >
                      <el-col
                        v-if="
                          !(
                            subItem.action &&
                            subItem.action.length === 0 &&
                            subItem.action_data &&
                            subItem.action_data.length === 0
                          )
                        "
                        :span="24"
                      >
                        <el-col :span="24">
                          <div class="action_title">
                            <span class="_h2">{{ subItem.menu_name }}</span><span class="_h1">【{{ item.menu_name }}】</span>
                          </div>
                        </el-col>
                        <el-col
                          v-if="subItem.action && subItem.action.length > 0"
                          :span="24"
                        >
                          <el-col :span="5">
                            <div class="yemian-main tc">
                              <el-checkbox
                                v-model="subItem.checkAll"
                                :disabled="isDetail"
                                :indeterminate="indeterminateCheck(subItem)"
                                @change="
                                  handleCheckAllChange(
                                    $event,
                                    index,
                                    item,
                                    subIndex
                                  )
                                "
                              >功能全选</el-checkbox>
                            </div>
                          </el-col>
                          <el-col :span="19">
                            <div class="yemian-main">
                              <el-checkbox-group
                                v-model="subItem.checkList"
                                @change="
                                  handleCheckedGroupChange(
                                    $event,
                                    index,
                                    item,
                                    subIndex
                                  )
                                "
                              >
                                <template v-for="children in subItem.action">
                                  <!-- :disabled="!rules.some(item => item.name == 'function_save')" -->
                                  <el-checkbox
                                    :key="'ruleChildren' + children.id"
                                    :disabled="isDetail"
                                    :label="children.id"
                                    @change="
                                      handleCheckedChange(
                                        $event,
                                        children.id,
                                        index,
                                        subIndex,
                                        item
                                      )
                                    "
                                  >{{ children.action_name }}</el-checkbox>
                                </template>
                              </el-checkbox-group>
                            </div>
                          </el-col>
                        </el-col>
                        <el-col
                          v-if="
                            subItem.action_data &&
                              subItem.action_data.length > 0
                          "
                          :span="24"
                        >
                          <el-col :span="5">
                            <div class="ziduan-main tc">
                              <el-checkbox
                                v-model="subItem.fieldAll"
                                :disabled="isDetail"
                                :indeterminate="indeterminateField(subItem)"
                                @change="
                                  handleFieldAllChange(
                                    $event,
                                    index,
                                    item,
                                    subIndex
                                  )
                                "
                              >字段全选</el-checkbox>
                            </div>
                          </el-col>
                          <el-col :span="19">
                            <div class="ziduan-main">
                              <el-checkbox-group
                                v-model="subItem.fieldList"
                                :disabled="isDetail"
                                @change="
                                  handleFieldGroupChange(
                                    $event,
                                    index,
                                    item,
                                    subIndex
                                  )
                                "
                              >
                                <template
                                  v-for="children in subItem.action_data"
                                >
                                  <!-- :disabled="!rules.some(item => item.name == 'function_save')" -->
                                  <el-checkbox
                                    :key="'ruleChildren' + children.id"
                                    :disabled="isDetail"
                                    :label="children.id"
                                    @change="
                                      handleFieldChange(
                                        $event,
                                        children.id,
                                        index,
                                        subIndex,
                                        item
                                      )
                                    "
                                  >{{ children.field_name }}</el-checkbox>
                                </template>
                              </el-checkbox-group>
                            </div>
                          </el-col>
                        </el-col>
                      </el-col>
                    </el-row>

                    <!-- {{ item.menu_name }} -->
                  </el-col>
                </el-row>
              </el-col>
            </div>
          </div>
        </el-form>
        <el-col :span="24" style="text-align: right">
          <el-button
            v-if="!isDetail"
            type="primary"
            @click="submitForm"
          >保 存
          </el-button>
          <el-button @click="showModelThis = false">{{
            isDetail ? "关 闭" : "取 消"
          }}</el-button>
        </el-col>
      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import asyncRequest from '@/apis/service/interest/role'
import roleLevel from '@/assets/js/roleLevel'
import { isChinese, isEmoticon } from '@/utils/validate'
export default {
  name: 'Role',
  props: ['showModel', 'id', 'isDetail'],
  data() {
    const validatename = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('角色名称不能为空！'))
      } else {
        if (value.lenght < 2 || value.lenght > 10) {
          callback(new Error('角色名称规则为2~10位汉字！'))
        } else if (!isChinese(value)) {
          console.log(9999)
          callback(new Error('角色名称规则为2~10位汉字！'))
        } else if (isEmoticon(value)) {
          console.log(2345)
          callback(new Error('角色名称规则为2~10位汉字！'))
        } else {
          callback()
        }
      }
    }
    return {
      loading: false,
      title: '添加角色',
      showModelThis: this.showModel,
      roleLevel: roleLevel,
      ruleForm: {
        role_name: '',
        level: '1'
      },
      action_data: [], // 字段数据
      action: [], // 功能数据
      // 当前角色
      roleActive: {
        rules: []
      },
      // 角色列表
      roleList: [],
      // 功能权限列表
      ruleList: [],
      dataList: [],
      actionList: [],
      rulesThis: this.rules,
      rules: {
        role_name: [
          {
            required: true,
            validator: validatename,
            trigger: 'blur'
          }
        ],
        level: [
          { required: true, message: '请选择角色等级', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    indeterminateCheck() {
      return (item) => {
        // 选中子节点的数量
        const selectItemLength = item.action.filter(
          (filitem) =>
            item.checkList.findIndex((finditem) => finditem === filitem.id) >
              -1
        ).length
        // 未选中子节点的数量
        const noSlectItemLength = item.action.filter(
          (filitem) =>
            item.checkList.findIndex((finditem) => finditem === filitem.id) ==
              -1
        ).length
        // // 当前节点的index
        // 存在选中子节点且存在未选中子节点为中间态
        return selectItemLength > 0 && noSlectItemLength > 0
      }
    },
    indeterminateField() {
      return (item) => {
        // console.log(item);
        // 选中子节点的数量
        const selectItemLength = item.action_data.filter(
          (filitem) =>
            item.fieldList.findIndex((finditem) => finditem === filitem.id) >
              -1
        ).length
        // 未选中子节点的数量
        const noSlectItemLength = item.action_data.filter(
          (filitem) =>
            item.fieldList.findIndex((finditem) => finditem === filitem.id) ==
              -1
        ).length
        // // 当前节点的index
        // 存在选中子节点且存在未选中子节点为中间态
        return selectItemLength > 0 && noSlectItemLength > 0
      }
    }
    // rules() {
    //   let tran =
    //     this.$store.state.common.ruleslist.find(
    //       item => item.name == "function_power"
    //     ) || {};
    //   return this.$store.state.common.ruleslist.filter(
    //     item => item.pid === tran.id
    //   );
    // },
  },
  watch: {
    showModel: function(val) {
      this.showModelThis = val
      if (val) {
        this.initForm()
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit('cancel')
      }
    }
  },
  methods: {
    // 全选/全不选
    handleCheckAllChange(checkAll, index, item, subIndex) {
      this.actionList[index].child[subIndex].checkAll = checkAll
      this.$set(this.actionList, index, item)
      this.actionList[index].child[subIndex].action.forEach((element) => {
        const findindex = this.actionList[index].child[
          subIndex
        ].checkList.findIndex((findItem) => findItem === element.id)
        if (checkAll && findindex == -1) {
          this.actionList[index].child[subIndex].checkList.push(element.id)
        } else if (!checkAll && findindex > -1) {
          this.actionList[index].child[subIndex].checkList.splice(findindex, 1)
        }
      })
    },
    // 全选/全不选
    handleFieldAllChange(fieldAll, index, item, subIndex) {
      this.actionList[index].child[subIndex].fieldAll = fieldAll
      this.$set(this.actionList, index, item)
      this.actionList[index].child[subIndex].action_data.forEach((element) => {
        const findindex = this.actionList[index].child[
          subIndex
        ].fieldList.findIndex((findItem) => findItem === element.id)
        if (fieldAll && findindex == -1) {
          this.actionList[index].child[subIndex].fieldList.push(element.id)
        } else if (!fieldAll && findindex > -1) {
          this.actionList[index].child[subIndex].fieldList.splice(findindex, 1)
        }
      })
    },
    // 复选框组内的选中/不选中
    handleCheckedGroupChange(event, index, item, subIndex) {
      // console.log(event, index, subIndex);
      this.actionList[index].child[subIndex].checkAll = this.actionList[
        index
      ].child[subIndex].action.every(
        (evitem) =>
          this.actionList[index].child[subIndex].checkList.findIndex(
            (finditem) => finditem === evitem.id
          ) > -1
      )
      this.$set(this.actionList, index, item)
    },
    // 复选框组内的选中/不选中
    handleFieldGroupChange(event, index, item, subIndex) {
      this.actionList[index].child[subIndex].fieldAll = this.actionList[
        index
      ].child[subIndex].action_data.every(
        (evitem) =>
          this.actionList[index].child[subIndex].fieldList.findIndex(
            (finditem) => finditem === evitem.id
          ) > -1
      )
      this.$set(this.actionList, index, item)
    },

    // 单项复选框选中/不选中

    handleCheckedChange(checked, id, index, subIndex, item) {
      // console.log(checked, id, index, subIndex);
      if (checked) {
        // 选中时检查pid的选中状态
        this.actionList[index].child[subIndex].checkList.indexOf(id) == -1 &&
          this.actionList[index].child[subIndex].checkList.push(id)
      } else {
        const find = this.actionList[index].child[subIndex].checkList.findIndex(
          (e) => e == id
        )
        if (find > -1) {
          this.actionList[index].child[subIndex].checkList.splice(find, 1)
        }
        this.actionList[index].child[subIndex].checkAll = false
      }
      this.$set(this.actionList, index, item)
      // console.log(this.actionList[index].child[subIndex]);
    },
    // 单项复选框选中/不选中
    handleFieldChange(checked, id, index, subIndex, item) {
      // console.log(checked, id, index, subIndex);
      if (checked) {
        // 选中时检查pid的选中状态
        this.actionList[index].child[subIndex].fieldList.indexOf(id) == -1 &&
          this.actionList[index].child[subIndex].fieldList.push(id)
      } else {
        const find = this.actionList[index].child[subIndex].fieldList.findIndex(
          (e) => e == id
        )
        if (find > -1) {
          this.actionList[index].child[subIndex].fieldList.splice(find, 1)
        }
        this.actionList[index].child[subIndex].fieldAll = false
      }
      this.$set(this.actionList, index, item)
      // console.log(this.actionList[index].child[subIndex]);
    },

    closeModel() {
      console.log('closeModel!!')
    },
    async initForm() {
      this.loading = true
      if (this.id === 'add') {
        this.title = '添加角色'
        // this.ruleForm.isAdmin = 0;
        this.rulesThis = this.rules
        await this.resetForm()
        await this.initActionList()
        this.loading = false
      } else {
        if (this.isDetail) {
          this.title = '角色'
          this.rulesThis = {}
        } else {
          this.title = '修改角色'
          this.rulesThis = this.rules
        }
        await this.resetForm()
        await this.initActionList()
        await this.initData()
        this.loading = false
      }
    },
    async initData() {
      const res = await asyncRequest.detail({ roleid: this.id })
      if (res.code === 0) {
        this.ruleForm = res.data
        if (res.data && res.data.action && res.data.action.length > 0) {
          this.action = res.data.action
        } else {
          this.action = []
        }
        if (
          res.data &&
          res.data.action_data &&
          res.data.action_data.length > 0
        ) {
          this.action_data = res.data.action_data
        } else {
          this.action_data = []
        }
        const arr = JSON.parse(JSON.stringify(this.actionList))
        arr.map((x) => {
          if (x.child && x.child.length > 0) {
            x.child.map((y) => {
              if (y.action && y.action.length > 0) {
                y.action.map((z) => {
                  const Aindex = this.action.findIndex((a) => a === z.id)
                  if (Aindex !== -1) {
                    y.checkList.push(this.action[Aindex])
                  }
                  return z
                })
                if (y.action.length === y.checkList.length) {
                  y.checkAll = true
                }
              }
              if (y.action_data && y.action_data.length > 0) {
                y.action_data.map((z) => {
                  const Bindex = this.action_data.findIndex((a) => a === z.id)
                  if (Bindex !== -1) {
                    y.fieldList.push(this.action_data[Bindex])
                  }
                  return z
                })
                if (y.action_data.length === y.fieldList.length) {
                  y.fieldAll = true
                }
              }
              return y
            })
          }
          return x
        })

        this.actionList = arr
        console.log(this.actionList)
      }
    },
    async initActionList() {
      const res = await asyncRequest.actionList({})
      if (res.code === 0) {
        const list = res.data
        console.log(list)
        let arr = list.filter((item) => item.child && item.child.length > 0)
        arr = arr.map((x) => {
          x.child.map((y) => {
            y.checkAll = false
            y.checkList = []
            y.fieldAll = false
            y.fieldList = []
            return y
          })
          return x
        })

        this.actionList = arr
        console.log(this.actionList)
      }
    },
    async resetForm() {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields()
          this.$refs.ruleForm.clearValidate()
          this.ruleForm = {
            role_name: '',
            level: '1'
          }
        }
      })
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          this.action_data = [] // 字段数据
          this.action = [] // 功能数据
          this.actionList.forEach((x) => {
            x.child.forEach((y) => {
              this.action_data.push(...y.fieldList)
              this.action.push(...y.checkList)
            })
          })
          if (this.action_data.length === 0 || this.action.length === 0) {
            this.$message.warning('请选择功能和字段!')
          } else {
            this.loading = true
            const model = {
              roleid: this.id,
              role_name: this.ruleForm.role_name,
              level: this.ruleForm.level,
              action: this.action,
              action_data: this.action_data
            }
            let res = {}
            if (this.id === 'add') {
              delete model['roleid']
              res = await asyncRequest.add(model)
            } else {
              res = await asyncRequest.update(model)
            }
            this.loading = false
            if (res.code === 0) {
              const title = this.id === 'add' ? '添加成功' : '修改成功'
              this.$notify.success({
                title,
                message: ''
              })
              this.showModelThis = false
              // 刷新
              this.$emit('refresh')
            }
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

   <style lang="scss" scoped>
.role {
  .quanxian-main {
    width: 100%;
    display: flex;
    .quanxian-title {
      width: 84px;
      position: relative;
      padding:8px 0 0 7px;

    }
    .quanxian {
      position: relative;
      width: calc(100% - 84px);
      height: 550px;
      overflow-y:scroll;
      .action_title {
        padding: 18px 18px 18px 18px;
        border-bottom: 1px solid rgba(242, 242, 242, 1);
        font-size: 17px;
        font-weight: 400;
        ._h1 {
          color: rgb(160, 207, 255);
          padding: 0 0 0 5px;
        }
        .xiegang {
          color: #000;
          padding: 0 6px;
        }
        ._h2 {
          color: #606266;
        }
      }
      .yemian-main {
        padding: 15px 0 0 0;
      }
      .ziduan-main {
        padding: 15px 0;
      }
    }
  }
}
</style>
