<template>
    <div class="userDetailContainer">
        <header-title :title="title"/>
        <div class="userForm">
            <el-form ref="form" :model="form" :rules="rules" label-position="left" label-width="140px">
                <el-row type="flex" justify="center">
                     <el-col :span="colSize">
                        <el-form-item required label="员工姓名：" prop="name">
                            <el-input :disabled="isDetail" v-model="form.name" placeholder="请输入员工姓名" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex" justify="center">
                    <el-col :span="colSize">
                        <el-form-item required label="员工账号：" prop="account">
                            <el-input :disabled="isDetail" v-model="form.account" placeholder="请输入员工账号" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex" justify="center">
                    <el-col :span="colSize">
                        <el-form-item required label="登录密码：" prop="password">
                            <el-input :disabled="isDetail" v-model="form.password" placeholder="请输入登录密码"/>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row type="flex" justify="center">
                    <el-col :span="colSize">
                        <el-form-item required label="权限：" prop="jurisdiction">
                        <div
                            v-for="(item, index) in jurisdictionList"
                            class="jurisdiction-checked-area"
                            :key="index"
                        >
                            <div class="checkbox-title">
                            <el-checkbox
                                :indeterminate="isIndeterminateList[item.name]"
                                v-model="isCheckAllList[item.name]"
                                @change="handleCheckAllChange(item.name)"
                            >
                                <span class="checkbox-title-text">
                                {{ item.title }}
                                </span>
                            </el-checkbox>
                            </div>
                            <!-- <div style="margin: 15px 0"></div> -->
                            <!-- <el-divider></el-divider> -->
                            <div class="checkbox-area">
                            <el-checkbox-group
                                v-model="checkedList[item.name]"
                                @change="handleCheckedChange(item.name)"
                            >
                                <el-checkbox
                                v-for="(citem, cindex) in item.children"
                                :label="citem.meta.jurisdiction"
                                :key="citem.name + cindex"
                                >{{ citem.meta.name }}</el-checkbox
                                >
                            </el-checkbox-group>
                            </div>
                            <!-- <el-divider></el-divider> -->
                        </div>                           
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div v-if="!isDetail" class="confirm">
                <el-button class="button-width" style="margin-right: 20px" @click="cancel">取消</el-button>
                <el-button class="button-width" type="primary" :loading="submitLoading" @click="beforeSubmit">确认
                </el-button>
            </div>
        </div>
    </div>
</template>

<script>
import HeaderTitle from '@/components/HeaderTitle/index';
import userAPI from "@/api/user";
import { frameIn } from "@/router/routes";
import {debounce} from '@/utils/index';
export default {
    name: 'userDetail',
    components: {HeaderTitle},
    data() {
        return {
            isDetail: false,
            id: this.$route.query.id ?? '',
            form: {
                name:"",
                account:"",
                password:"",
                jurisdiction: ""
            },
            submitLoading: false,
            title: '',
            colSize: 18,
            checkedList: {},
            checkedAllList: {},
            isIndeterminateList: {},
            isCheckAllList: {},
            originalJurisdiction: [], //初始的权限
            jurisdictionList: [],
            rules: {
                name: [
                    {
                        required: true,
                        trigger: ['blur', 'change'],
                        message: '请输入员工姓名',
                    },
                ],
                account: [
                    {
                        required: true,
                        trigger: ['blur', 'change'],
                        message: '请输入员工账号',
                    },
                ],
                password: [
                    {
                        required: true,
                        trigger: ['blur', 'change'],
                        message: '请输入登录密码',
                    },
                    {
                        trigger: 'blur',
                        validator: (rule, value, callback) => {
                            let passwordreg = /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[\W_]).{8,}$/
                            if (!passwordreg.test(value)) {
                                callback(new Error('请输入不少于8位的数字+字母+特殊符号组合'))
                            } else {
                                callback()
                            }
                        }
                    }
                ],
                jurisdiction: [
                    {
                        required: true,
                        trigger: ['blur', 'change'],
                        message: '请选择权限',
                    },
                ],
            },
        };
    },
    mounted() {
        this.initJurisdiction();
        this.$route.query.id ? this.initData() : false;
        this.title = this.$route.meta.name;
        this.isDetail = this.$route.query.isDetail;
    },
    methods: {
    afterInitInfo() {
      // console.log(this.form);
      this.originalJurisdiction = !this.form.jurisdiction
        ? []
        : this.form.jurisdiction.split(",");
      this.originalJurisdiction = Array.from(
        new Set(this.originalJurisdiction)
      ); //去重 ， 只留下唯一权限
      if (this.originalJurisdiction.length > 0) {
        this.originalJurisdiction.forEach((item) => {
          for (let key in this.checkedAllList) {
            let result = this.checkedAllList[key].find(
              (citem) => item === citem
            );
            if (result) {
              this.checkedList[key].push(result);
              let checkCount = this.checkedList[key].length;
              this.$set(
                this.isIndeterminateList,
                key,
                checkCount > 0 && checkCount < this.checkedAllList[key].length
              );
              this.$set(
                this.isCheckAllList,
                key,
                checkCount === this.checkedAllList[key].length
              );
            }
            //   console.log("result: ", result);
          }
        });
      }
      // console.log("this.originalJurisdiction: ", this.originalJurisdiction);
    },

    initJurisdiction() {
      let routeList = frameIn[1].children.filter((item) => {
        return !item.hidden && (item.meta.parentSelf || item.meta.parent);
      });
      // console.log("routeList11111111111: ", routeList,frameIn[1]);
      let result = [];
      routeList.forEach((item) => {
        // console.log("item: ", item);
        let parentSelf = result.find(
          (citem, cindex) => citem && ((item.meta.parentSelf && (citem.name === item.meta.parentSelf.name)) || (item.meta.parent && (citem.name === item.meta.parent.name)))
        );
        if (!parentSelf) {
          result.push({
            name: item.meta.parentSelf ? item.meta.parentSelf.name : (item.meta.parent ? item.meta.parent.name : ''),
            title: item.meta.parentSelf ? item.meta.parentSelf.title : (item.meta.parent ? item.meta.parent.title : ''),
            children: [
              {
                ...item,
              },
            ],
          });
        } else {
          parentSelf.children.push(item);
        }
        // console.log("parentSelf: ", parentSelf);
      });
      // console.log("result: ", result);
      this.jurisdictionList = [...result];
      this.jurisdictionList.forEach((item) => {
        // console.log("item: ", item);
        //初始化checkedList
        if (!this.checkedList[item.name]) {
          this.$set(this.checkedList, item.name, []);
        }
        if (!this.checkedAllList[item.name]) {
          this.$set(this.checkedAllList, item.name, []);
        }
        if (!this.isIndeterminateList[item.name]) {
          this.$set(this.isIndeterminateList, item.name, false);
        }
        if (!this.isCheckAllList[item.name]) {
          this.$set(this.isCheckAllList, item.name, false);
        }

        if (!!item.children && item.children.length > 0) {
          item.children.forEach((citem) => {
            // console.log("citem: ", citem);
            this.checkedAllList[item.name].push(citem.meta.jurisdiction);
          });
        }
      });
      // console.log("this.jurisdictionList: ", this.jurisdictionList);
      // routeList.forEach(item =>{})
    },
    handleCheckAllChange(key) {
      //   console.log("key: ", key);
      this.$set(
        this.checkedList,
        key,
        this.isCheckAllList[key] ? this.checkedAllList[key] : []
      );
      this.$set(this.isIndeterminateList, key, false);
      this.handleJurisdiction();
      //   console.log("index: ", index);
    },

    handleCheckedChange(key) {
      // console.log("key: ", key);
      let checkCount = this.checkedList[key].length;
      this.$set(
        this.isIndeterminateList,
        key,
        checkCount > 0 && checkCount < this.checkedAllList[key].length
      );
      this.$set(
        this.isCheckAllList,
        key,
        checkCount === this.checkedAllList[key].length
      );
      this.handleJurisdiction();
    },

    handleJurisdiction() {
      let checkedJurisdictionArr = [];
      for (let i in this.checkedList) {
        if (!!this.checkedList[i] && this.checkedList[i].length > 0) {
          this.checkedList[i].forEach((item) => {
            if (!!item) checkedJurisdictionArr.push(item);
          });
        }
      }
      this.form.jurisdiction = checkedJurisdictionArr.join(",");
      //   console.log("this.form: ", this.form);
    },
        initData() {
            userAPI.getUserById({id: this.id}).then(res => {
                if (res.code === 1000) {
                    this.form = res.data
                    this.afterInitInfo()
                } else {
                    this.form = []
                }
            }).catch(err => {
                this.form = []
                this.$message.error("获取数据失败，请重试")
            })
        },
        submituser() {
            let params = {id: this.id ? this.id : null, ...this.form};
            userAPI.addOrUpdateUser(params).then(res => {
                if (res.code === 1000) {
                    this.$message.success(this.title + "成功！");
                    this.submitLoading = false;
                    this.cancel();
                } else {
                    this.$message.error(res.msg);
                    this.submitLoading = false;
                }
            }).catch(err => {
                console.error(err)
                this.$message.error(this.title + "失败！");
                this.submitLoading = false
            })
        },
        beforeSubmit: debounce(function (){
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (this.submitLoading) {
                        return
                    }
                    this.submitLoading = true;
                    this.submituser()
                }
            });
        },
            2000,
            true
        ),
        cancel() {
            this.$store.dispatch('tagsView/delView', this.$route);
            this.$router.go(-1)
        },
    },
}
</script>

<style scoped lang="scss">
.userDetailContainer {
    width: 100%;
    height: 100%;
    overflow-x: hidden;
    overflow-y: auto;

    /*添加css样式*/
    ::v-deep  input::-webkit-outer-spin-button,
    ::v-deep  input::-webkit-inner-spin-button {
        -webkit-appearance: none;
    }

    ::v-deep  input[type="number"] {
        -moz-appearance: textfield;
    }

    .userForm {
        padding-top: 3rem;

        ::v-deep  .el-input.is-disabled .el-input__inner {
            color: $color-333;
        }

        .secondaryTitle {
            line-height: 1.5rem;
            font-weight: bold;
            padding-left: 6px;
            border-left: 3px solid $theme-color;
            margin: 1rem 0;
        }

        .form-item {
            width: 45%;
        }

        .confirm {
            width: 90%;
            margin-top: 60px;
            margin-bottom: 40px;
            text-align: center;
        }
    }

    ::v-deep  .el-form-item__content {
        text-align: left;
    }

    ::v-deep  .el-date-editor {
        width: 600px;
    }

    ::v-deep  .el-select {
        width: 600px;
    }

    ::v-deep  .el-cascader {
        width: 600px;
    }

    ::v-deep  .el-input {
        width: 600px;
    }

    .button-width {
        width: 120px;
    }
  .jurisdiction-checked-area {
    // border: 1px solid rgb(209, 204, 204);
    // margin-bottom: 5px;
    .checkbox-title {
      background-color: #f0f2f5;
      padding-left: 5px;

      .checkbox-title-text {
        font-size: 20px;
        font-weight: bold;
      }
    }

    .checkbox-area {
      padding-left: 10px;
    }
  }
}
</style>
