<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="username">
              <span slot="label">
                用户名称&nbsp;
                <a-tooltip title="用户名称不为邮箱格式且sso中无当前用户时需设置密码">
                  <a-icon type="question-circle-o" />
                </a-tooltip>
              </span>
              <a-input v-model="model.username" placeholder="请输入用户名称" :disabled="userDisabled" @blur="handleBlur"></a-input>
            </a-form-model-item>
          </a-col>
          <template v-if="!isEmail">
            <a-col :span="24">
              <a-form-model-item label="登录密码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="password">
                <a-input-password autocomplete="new-password" v-model="model.password" placeholder="请输入登录密码" />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="确认密码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="confirmpassword" >
                <a-input-password autocomplete="new-password" v-model="model.confirmpassword" @blur="handleConfirmBlur" placeholder="请再次输入登录密码"/>
              </a-form-model-item>
            </a-col>
          </template>
          <a-col :span="24">
            <a-form-model-item label="描述" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-input v-model="model.remark" placeholder="请输入描述"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="是否为系统管理员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="role">
              <a-switch v-model="model.isSystem" checked-children="是" un-checked-children="否" @change="roleChange" :disabled="model.isSsoAdmin"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="所拥有的权限" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="role">
              <a-table
                v-if="tpmTreeData && tpmTreeData.length"
                ref="table"
                size="middle"
                :scroll="{x:true}"
                bordered
                rowKey="interlockSystemId"
                :columns="columns"
                :dataSource="tpmTreeData"
                :loading="loading"
                :pagination="false"
                defaultExpandAllRows
                class="interlock-user-limit"
                >
                <!-- class="j-table-force-nowrap" -->
                <!-- @change="handleTableChange" -->
                <span slot="manageTitle">
                  <a-checkbox v-model="manageHeader" :indeterminate="indeterminateManageHeader" :disabled="model.isSystem" @change="changeManageHeader"/>
                  <div>管理</div>
                </span>
                <span slot="manage" slot-scope="text, record">
                  <span v-if="record.interlockType === '0' && !record.children && !model.isSystem">-</span>
                  <a-checkbox v-else v-model="record.manage" :indeterminate="record.indeterminateManage" :disabled="model.isSystem"/>
                  <!-- <a-checkbox v-model="record.manage" :indeterminate="record.indeterminateManage" :disabled="model.isSystem"/> -->
                </span>
                <span slot="viewTitle">
                  <a-checkbox v-model="viewHeader" :indeterminate="indeterminateViewHeader" :disabled="model.isSystem" @change="changeViewHeader"/>
                  <div>查看</div>
                </span>
                <span slot="view" slot-scope="text, record">
                  <span v-if="record.interlockType === '0' && !record.children && !model.isSystem">-</span>
                  <a-checkbox v-else v-model="record.view" :indeterminate="record.indeterminateView" :disabled="model.isSystem"/>
                  <!-- <a-checkbox v-model="record.view" :indeterminate="record.indeterminateView" :disabled="model.isSystem"/> -->
                </span>
              </a-table>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import cookie from 'js-cookie'

  export default {
    name: 'InterlockUserForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        userDisabled: false, // 修改时用户名不可修改
        model:{
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          username: [
            { required: true, message: '请输入用户名称!', },
            { validator: (rule, value, callback) => validateDuplicateValue('interlock_user', 'username', value, this.model.id, callback)},
            // {
            //   pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
            //   message: '邮箱格式不正确'
            // },
          ],
          password: [
            { required: true,
              // pattern:/^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,}$/,
              message: '密码由8位数字、大小写字母和特殊符号组成!' },
            { validator: this.validateToNextPassword,trigger: 'change' }
          ],
          confirmpassword: [
            { required: true, message: '请重新输入登录密码!',},
            { validator: this.compareToFirstPassword,}
          ],
        },
        url: {
          add: "/interlockUser/interlockUser/addUser",
          edit: "/interlockUser/interlockUser/editUser",
          queryById: "/interlockUser/interlockUser/queryUserById"
        },
        // 权限树-装置系统
        loading: false,
        tpmTreeData: [],
        expandedRowKeys: [],
        columns: [
          {
            title:'',
            dataIndex: 'interlockName'
          },
          {
            // title:'管理',
            align:"center",
            dataIndex: 'manage',
            width:147,
            slots: { title: 'manageTitle' },
            scopedSlots: { customRender: 'manage' },
            customCell: (record, index)=>{ return this.customCell(record, index, 'manage')}
          },
          {
            // title:'查看',
            align:"center",
            dataIndex: 'view',
            width:147,
            slots: { title: 'viewTitle' },
            scopedSlots: { customRender: 'view' },
            customCell: (record, index)=>{ return this.customCell(record, index, 'view')}
          },
        ],
        manageHeader: false,
        indeterminateManageHeader: false,
        viewHeader: false,
        indeterminateViewHeader: false,
        isEmail: true, // 用户是否为邮箱格式
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
      // isSsoManage(){
      //   return cookie.get('SSORole') === 'globalAdmin'
      //   // return this.$store.getters.userInfo.role === '0'
      // },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      validateToNextPassword (rule, value, callback) {
        const confirmpassword=this.model.confirmpassword;
        if (value && confirmpassword && value !== confirmpassword) {
          callback('两次输入的密码不一样！');
        }
        if (value && this.confirmDirty) {
          this.$refs.form.validateField(['confirmpassword']);
        }
        callback();
      },
      compareToFirstPassword (rule, value, callback) {
        if (value && value !== this.model.password) {
          callback('两次输入的密码不一样！');
        } else {
          callback()
        }
      },
      handleConfirmBlur(e) {
        const value = e.target.value;
        this.confirmDirty = this.confirmDirty || !!value
      },
      handleBlur(){
        const emailRegExp = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
        if(emailRegExp.test(this.model.username)){
          // 判断sso中是否有当前账户
        }
        this.isEmail = emailRegExp.test(this.model.username)
      },
      // 新增
      async add () {
        this.confirmLoading = true
        await getAction(`/base/interlockBase/list`).then(res=>{
          // 重组数据
          var arr = res.map(item => {
            var reValue = {}
            reValue.interlockName = item.interlockName
            reValue.interlockApparatusId = item.pid
            reValue.interlockSystemId = item.id
            reValue.interlockType = item.interlockType
            reValue.iotedgeGroupId = item.iotedgeGroupId
            reValue.limitType = ''
            reValue.manage = false
            reValue.view = false
            reValue.indeterminateManage = false
            reValue.indeterminateView = false
            return reValue
          })
          // arr.push({
          //   interlockName: '所有',
          //   interlockApparatusId: '',
          //   interlockSystemId: '0',
          //   manage: false,
          //   view: false,
          //   indeterminateManage: false,
          //   indeterminateView: false,
          // })
          this.tpmTreeData = this.handleTree(arr, "interlockSystemId", "interlockApparatusId")
          this.confirmLoading = false
        })
      },
      // 编辑
      async edit (record) {
        this.confirmLoading = true
        var interlockOrgData = []
        // 获取装置设置数据
        await getAction(`/base/interlockBase/list`).then(res=>{
          interlockOrgData = res
        })
        // 获取当前选择账户的详情以及权限等
        getAction(this.url.queryById, {id: record.id}).then(response => {
          this.model = Object.assign({}, response.result);
          this.model.isSystem = this.model.role === '0' ? true : false
          // console.log('model', this.model)
          var systemLimitList = response.result.systemLimitList
          // 重组数据
          var arr = interlockOrgData.map(ele => {
            var value = systemLimitList.find(item => item.interlockSystemId === ele.id)
            // console.log(value)
            var reValue = {}
            if(value){reValue.id = value.id}
            reValue.interlockName = ele.interlockName
            reValue.interlockApparatusId = ele.pid
            reValue.interlockSystemId = ele.id
            reValue.interlockType = ele.interlockType
            reValue.iotedgeGroupId = ele.iotedgeGroupId
            reValue.limitType = ''
            reValue.manage = false
            reValue.view = false
            reValue.indeterminateManage = false
            reValue.indeterminateView = false
            if(this.model.role === '0'){
              reValue.manage = true
            }
            if(this.model.role !== '0' && value){
              // reValue.id = value.id
              reValue.limitType = value.limitType
              reValue.manage = value.limitType === '0' ? true : false
              reValue.view = value.limitType === '1' ? true : false
            }
            return reValue
          })
          // console.log(arr)
          this.tpmTreeData = this.handleTree(arr, "interlockSystemId", "interlockApparatusId")
          // console.log(this.tpmTreeData)
          // 根据子系统回显父装置的多选框样式
          this.tpmTreeData.forEach(ele => {
            if(ele.children && ele.children.length > 0){
              // 设置每一个父装置管理选择框样式
              var chooseLengthM = ele.children.filter(item => item.manage).length
              ele.indeterminateManage = !!chooseLengthM && chooseLengthM < ele.children.length
              ele.manage = chooseLengthM === ele.children.length
              // 设置每一个父装置查看选择框样式
              var chooseLengthV = ele.children.filter(item => item.view).length
              ele.indeterminateView = !!chooseLengthV && chooseLengthV < ele.children.length
              ele.view = chooseLengthV === ele.children.length
            }
          })
          // 根据装置设置总管理/查看的多选框样式
          // 设置总的管理/查看多选框样式
          var hasSystemLength = this.tpmTreeData.filter(item => !!item.children).length
          var chooseLengthMH = this.tpmTreeData.filter(item => item.manage || (!item.manage && item.indeterminateManage)).length
          this.indeterminateManageHeader = !!chooseLengthMH && chooseLengthMH < hasSystemLength
          this.manageHeader = chooseLengthMH === hasSystemLength
          var chooseLengthVH = this.tpmTreeData.filter(item => item.view || (!item.view && item.indeterminateView)).length
          this.indeterminateViewHeader = !!chooseLengthVH && chooseLengthVH < hasSystemLength
          this.viewHeader = chooseLengthVH === hasSystemLength

          this.visible = true;
          this.confirmLoading = false
        })
      },
      // 表头管理多选框切换选择时
      changeManageHeader(e){
        // console.log(e.target.checked)
        if(e.target.checked){
          // 自身样式相应改变
          this.viewHeader = false
          this.indeterminateViewHeader = false
          this.indeterminateManageHeader = false
          for (let i = 0; i < this.tpmTreeData.length; i++) {
            // 父装置样式改变
            const element = this.tpmTreeData[i];
            element.manage = element.children ? true : false
            element.indeterminateManage = false
            element.view = false
            element.indeterminateView = false
            if(element.children && element.children.length > 0){
              element.children.forEach(item => {
                // 子系统样式改变  
                item.manage = true
                item.view = false
              })
            }
          }
        } else {
          for (let i = 0; i < this.tpmTreeData.length; i++) {
            const element = this.tpmTreeData[i];
            element.manage = false
            element.view = false
            if(element.children && element.children.length > 0){
              element.children.forEach(item => {
                item.manage = false
                item.view = false
              })
            }
          }
        }
      },
      // 表头查看多选框切换选择时
      changeViewHeader(e){
        if(e.target.checked){
          this.manageHeader = false
          this.indeterminateManageHeader = false
          this.indeterminateViewHeader = false
          for (let i = 0; i < this.tpmTreeData.length; i++) {
            // 父装置样式改变
            const element = this.tpmTreeData[i];
            element.view = element.children ? true : false
            element.indeterminateManage = false
            element.manage = false
            element.indeterminateView = false
            if(element.children && element.children.length > 0){
              element.children.forEach(item => {
                // 子系统样式改变  
                item.view = true
                item.manage = false
              })
            }
          }
        } else {
          for (let i = 0; i < this.tpmTreeData.length; i++) {
            const element = this.tpmTreeData[i];
            element.view = false
            element.manage = false
            if(element.children && element.children.length > 0){
              element.children.forEach(item => {
                item.view = false
                item.manage = false
              })
            }
          }
        }
      },
      // 角色切换时
      roleChange(e){
        // this.$set(this.model, 'isSystem', e)
        this.model = {...this.model}
        if(e){
          // 当前为管理员
          this.manageHeader = true
          this.indeterminateViewHeader = false
          this.indeterminateManageHeader = false
          for (let i = 0; i < this.tpmTreeData.length; i++) {
            const element = this.tpmTreeData[i];
            element.manage = true
            element.indeterminateManage = false
            element.indeterminateView = false
            if(element.children && element.children.length > 0){
              element.children.forEach(item => {
                item.manage = true
                item.view = false
              })
            }
          }
        } else {
          // 当前为管理员
          this.manageHeader = false
          for (let i = 0; i < this.tpmTreeData.length; i++) {
            const element = this.tpmTreeData[i];
            element.manage = false
            if(element.children && element.children.length > 0){
              element.children.forEach(item => {
                item.manage = false
                item.view = false
              })
            }
          }
        }
      },
      customCell(record, rowIndex, value){
        return {
          props: {
          },
          on: { // 事件
            click: (event) => {
              // console.log(event)
              // console.log(event.target.checked)
              // console.log(record, rowIndex, value)
              // 当前点击为装置且点击为装置选择框
              if(record.interlockType === '0' && event.target.type === 'checkbox'){
                // 全选管理
                if(value === 'manage' && event.target.checked){
                  // 当前父装置多选框样式以及管理查看取反设置
                  record.indeterminateView = false
                  record.indeterminateManage = false
                  record.manage = true
                  record.view = false
                  // 根据装置选择情况判断子系统的选择状态
                  if(record.children && record.children.length > 0){
                    record.children.forEach(ele => {
                      ele.manage = true
                      ele.view = false
                    })
                  }
                }
                // 全选查看
                if(value === 'view' && event.target.checked){
                  // 当前父装置多选框样式以及管理查看取反设置
                  record.indeterminateManage = false
                  record.indeterminateView = false
                  record.view = true
                  record.manage = false
                  // 根据装置选择情况判断子系统的选择状态
                  if(record.children && record.children.length > 0){
                    record.children.forEach(ele => {
                      ele.view = true
                      ele.manage = false
                    })
                  }
                }
                // 取消全选
                if(!event.target.checked){
                  record.indeterminateManage = false
                  record.indeterminateView = false
                  record.view = false
                  record.manage = false
                  if(record.children && record.children.length > 0){
                    record.children.forEach(ele => {
                      ele.manage = false
                      ele.view = false
                    })
                  }
                }
              }
              // 当前点击为装置且点击为系统选择框
              if(record.interlockType === '1' && event.target.type === 'checkbox'){
                console.log(record, rowIndex, value)
                // 管理和查看相互取反，并设置对应父装置的多选框样式
                // interlockApparatusId相当于pid，interlockSystemId相当于id
                // 某系统选择管理时
                if(value === 'manage'){
                  // 取反
                  // if(event.target.checked){record.view = false}
                  record.view = event.target.checked ? !event.target.checked : record.view
                  // 设置为true/false是为了下面判断length
                  record.manage = event.target.checked
                  var pidValue = this.tpmTreeData.find(item => item.interlockSystemId === record.interlockApparatusId)
                  // 设置当前子系统父装置管理选择框样式
                  var chooseLengthM = pidValue.children.filter(item => item.manage).length
                  pidValue.indeterminateManage = !!chooseLengthM && chooseLengthM < pidValue.children.length
                  pidValue.manage = chooseLengthM === pidValue.children.length
                  // 设置当前子系统父装置查看选择框样式
                  var chooseLengthV = pidValue.children.filter(item => item.view).length
                  pidValue.indeterminateView = !!chooseLengthV && chooseLengthV < pidValue.children.length
                  pidValue.view = chooseLengthV === pidValue.children.length
                }
                if(value === 'view'){
                  // 取反
                  record.manage = event.target.checked ? !event.target.checked : record.manage
                  // 设置为true/false是为了下面判断length
                  record.view = event.target.checked
                  // 设置当前子系统父装置查看选择框样式
                  var pidValue = this.tpmTreeData.find(item => item.interlockSystemId === record.interlockApparatusId)
                  var chooseLengthV = pidValue.children.filter(item => item.view).length
                  pidValue.indeterminateView = !!chooseLengthV && chooseLengthV < pidValue.children.length
                  pidValue.view = chooseLengthV === pidValue.children.length
                  // 设置当前子系统父装置管理选择框样式
                  var chooseLengthM = pidValue.children.filter(item => item.manage).length
                  pidValue.indeterminateManage = !!chooseLengthM && chooseLengthM < pidValue.children.length
                  pidValue.manage = chooseLengthM === pidValue.children.length
                }
              }
              // 设置总的管理/查看多选框样式
              // console.log(this.tpmTreeData)
              var hasSystemLength = this.tpmTreeData.filter(item => !!item.children).length
              // console.log(hasSystemLength)
              // 管理选择但没完全选择样式
              var hasChooseLengthMH = this.tpmTreeData.filter(item => item.manage || (!item.manage && item.indeterminateManage)).length
              // 管理全选样式
              var chooseAllLengthMH = this.tpmTreeData.filter(item => item.manage).length
              this.indeterminateManageHeader = !!hasChooseLengthMH && hasChooseLengthMH <= hasSystemLength && chooseAllLengthMH !== hasSystemLength
              this.manageHeader = chooseAllLengthMH === hasSystemLength
              // 查看选择但没完全选择样式
              var hasChooseLengthVH = this.tpmTreeData.filter(item => item.view || (!item.view && item.indeterminateView)).length
              // 查看全选样式
              var chooseAllLengthVH = this.tpmTreeData.filter(item => item.view).length
              this.indeterminateViewHeader = !!hasChooseLengthVH && hasChooseLengthVH <= hasSystemLength && chooseAllLengthVH !== hasSystemLength
              this.viewHeader = chooseAllLengthVH === hasSystemLength
            },
          },
        };
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            // console.log(this.tpmTreeData)
            // 二维转一维
            var arr = []
            this.tpmTreeData.forEach(item => {
              if(item.children){
                arr.push(...item.children)
              }
            })
            // console.log(arr)
            this.model.systemLimitList = arr.map(item => {
              if(item.manage){item.limitType = '0'}
              if(item.view){item.limitType = '1'}
              if(!item.manage && !item.view){item.limitType = ''}
              return item
            })
            this.model.role = this.model.isSystem ? '0' : '1'
            // console.log(su)
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            // 1820384671259701250 -- 联锁系统管理员	
            // 1820343133955698689 -- 联锁普通SSO用户	
            this.model.roleId = this.model.isSystem ? '1820384671259701250' : '1820343133955698689'
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },
    }
  }
</script>
<style lang="less">
  .interlock-user-limit{
    tr{
      td{
        padding: 5px 8px !important;
      }
    }
  }
</style>
