<template>
  <el-form
    inline
    :model="form"
    :rules="rules"
    ref="form"
    label-width="100px">
    <div class="dialog-info">
      <el-form-item
        verify
        class="is-required"
        label="账号"
        prop="name">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item
        verify
        class="is-required"
        label="所属角色"
        prop="selectRole">
        <el-select
          value-key="id"
          v-model="form.selectRole"
          multiple
          collapse-tags
          placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.nick_name"
            :value="item">
          </el-option>
        </el-select>
      </el-form-item>

      <template v-if="dialogType === 'add'">
        <el-form-item
          verify
          label="密码"
          prop="password">
          <el-input
            v-model="form.password"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item
          verify
          label="确认密码"
          prop="checkPass">
          <el-input
            v-model="form.checkPass"
            type="password"
          ></el-input>
        </el-form-item>
      </template>

      <template v-else>
        <el-form-item
          label="密码"
          prop="password">
          <el-input
            v-model="form.password"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="确认密码"
          prop="checkPass">
          <el-input
            v-model="form.checkPass"
            type="password"
          ></el-input>
        </el-form-item>
      </template>

      <el-form-item
        verify
        class="is-required"
        label="昵称"
        prop="nick_name">
        <el-input v-model="form.nick_name"></el-input>
      </el-form-item>
      <el-form-item
        label="过期时间"
        prop="use_end_time">
        <el-date-picker
          style="width:210px"
          v-model="form.use_end_time"
          default-time="23:59:59"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        :verify="verifyPhone"
        label="手机"
        prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>

      <el-form-item label="绑定景点">
        <el-select
          @change="selectAll"
          value-key="id"
          v-model="form.scenic"
          multiple
          collapse-tags
          placeholder="请选择">
          <el-option
            :value="0"
            label="全部">
          </el-option>
          <el-option
            v-for="item in scenicList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="绑定售票点">
        <el-select
          v-model="form.ticket_spot_id"
          placeholder="请选择">
          <el-option
            v-for="item in ticketSpotList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item
        label="子项目"
        v-if="checkPermission('ticket_type_scenic:sub_project_manager')">
        <el-select
          v-model="form.sub_project_id"
          placeholder="请选择">
          <el-option
            v-for="item in subProjectList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item> -->
    </div>
    <div class="dialog-btn-wrap">
      <el-button
        v-if="dialogType === 'edit'"
        @click="handleClose">
        关闭
      </el-button>
      <el-button
        v-if="dialogType === 'add'"
        @click="reset">
        重置
      </el-button>
      <el-button
        @click="submit"
        type="primary">
        保存
      </el-button>
    </div>
  </el-form>
</template>

<script>
import { updateAccount, addAccount } from '@/api/systemSetting/account'
import { getRoleList } from '@/api/systemSetting/role'
import { verifyPhone } from '@/utils/validate'
import { isEqual } from 'lodash'
import { getTicketSpotList } from '@/api/ticketSpot'
import { Base64 } from 'js-base64'
import { encrypt } from '@/utils'
const Store = require('electron-store')
const localStore = new Store()
// import { subProjectList } from '@/api/ticketType'
// import checkPermission from '@/utils/checkPermission'

export default {
  props: {
    dialogType: {
      type: String,
      default: ''
    },
    accountItem: {
      type: Object,
      default: () => {}
    },
    scenicList: {
      type: Array,
      default: () => []
    }
  },
  computed: {
    roles () {
      return this.form.selectRole.map(item => {
        return { id: item.id }
      })
    },
    isAll () {
      let scenic = this.form.scenic
      let old = this.scenicList.map(i => i.id)
      old.unshift(0)
      return isEqual(scenic, old)
    }
  },
  data () {
    var validatePass = (rule, value, callback) => {
      if (this.form.checkPass !== '') {
        this.$refs.form.validateField('checkPass')
      }
      callback()
    }
    var validatePass2 = (rule, value, callback) => {
      if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      roleList: [],
      oldOptions: [[]],
      ticketSpotList: [],
      // subProjectList: [],
      form: {
        name: '',
        nick_name: '',
        password: '',
        checkPass: '',
        scenic: [],
        ticket_spot_id: '',
        selectRole: [],
        use_end_time: '',
        phone: ''
        // sub_project_id: ''
      },
      rules: {
        password: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // checkPermission,
    verifyPhone,
    selectAll (val) {
      let allValues = this.scenicList.map(i => i.id)
      allValues.unshift(0)

      let isAll
      let scenic = this.form.scenic
      let old = this.scenicList.map(i => i.id)

      isAll = isEqual(scenic, old)
      // 用来储存上一次的值，可以进行对比
      const oldVal = this.oldOptions.length === 1 ? (isAll ? [0] : []) : this.oldOptions[1]

      // 若是全部选择
      if (val.includes(0)) this.form.scenic = allValues

      // 取消全部选中  上次有 当前没有 表示取消全选
      if (oldVal.includes(0) && !val.includes(0)) this.form.scenic = []

      // 点击非全部选中  需要排除全部选中 以及 当前点击的选项
      // 新老数据都有全部选中
      if (oldVal.includes(0) && val.includes(0)) {
        const index = val.indexOf(0)
        val.splice(index, 1) // 排除全选选项
        this.form.scenic = val
      }

      // 全选未选 但是其他选项全部选上 则全选选上 上次和当前 都没有全选
      if (!oldVal.includes(0) && !val.includes(0)) {
        if (val.length === allValues.length - 1) this.form.scenic = [0].concat(val)
      }

      // 储存当前最后的结果 作为下次的老数据
      this.oldOptions[1] = this.form.scenic
    },
    handleClose () {
      this.$parent.handleClose()
    },
    reset () {
      this.$refs.form.resetFields()
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.scenic.includes(0)) {
            const index = this.form.scenic.indexOf(0)
            this.form.scenic.splice(index, 1) // 排除全选选项
          }

          this.form.manager_scenic_matrix = this.form.scenic.map(i => {
            return {
              scenic_id: i,
              manager_id: this.accountItem ? this.accountItem.id : null
            }
          })

          if (this.dialogType === 'add') {
            this.addAccount()
          } else {
            this.updateAccount()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    addAccount () {
      this.form.creator = this.$store.state.user.name
      const params = { ...this.form }
      if (localStore.get('encryption')) {
        params.password = Base64.encode('CTICKET' + params.password)
        params.checkPass = Base64.encode('CTICKET' + params.checkPass)
      }
      if (localStore.get('encryption_aes')) {
        params.password = encrypt(params.password)
        params.checkPass = encrypt(params.checkPass)
      }
      addAccount(params).then(res => {
        this.$message.success('添加成功')
        this.reset()
        this.handleClose()
        this.$emit('updateList')
      })
    },
    updateAccount () {
      const params = { ...this.form }
      if (localStore.get('encryption')) {
        params.password = Base64.encode('CTICKET' + params.password)
        params.checkPass = Base64.encode('CTICKET' + params.checkPass)
      }
      if (localStore.get('encryption_aes')) {
        params.password = encrypt(params.password)
        params.checkPass = encrypt(params.checkPass)
      }
      updateAccount(params).then(res => {
        this.$message.success('保存成功')
        this.reset()
        this.handleClose()
        this.$emit('updateList')
      })
    },
    getRoleList () {
      getRoleList().then(res => {
        this.roleList = res?.data
      })
    },
    getTicketSpotList () {
      this.loading = true
      return getTicketSpotList({
        pageNum: 1,
        pageSize: 10000
      }).then(res => {
        this.ticketSpotList = res.list
      })
    }
    // getSubProjectList () {
    //   this.loading = true
    //   return subProjectList({
    //     pageNum: 1,
    //     pageSize: 10000
    //   }).then(res => {
    //     this.subProjectList = res?.data.list
    //   })
    // }
  },
  watch: {
    visible (val) {
      // 获取角色列表
      val && this.getRoleList()
      // 重置表单
      this.getTicketSpotList()
      // this.getSubProjectList()
      this.reset()
      this.form.ticket_spot_id = ''
      this.form.scenic = []
      // 初始化编辑数据
      if (val && this.dialogType === 'edit' && this.accountItem) {
        let scenic = this.accountItem.manager_scenic_matrix.map(i => i.id)
        let old = this.scenicList.map(i => i.id)

        if (isEqual(old, scenic)) {
          scenic.unshift(0)
        }

        this.form = Object.assign({}, this.form, this.accountItem, {
          scenic: scenic,
          selectRole: JSON.parse(JSON.stringify(this.accountItem.roles)),
          password: '',
          checkPass: ''
        })
      }
    },
    roles (val) {
      this.$set(this.form, 'roles', val)
    }
  }
}
</script>
