<template>
  <el-dialog
    v-loading="loading"
    :title="title"
    :center="true"
    align="left"
    top="10vh"
    width="750px"
    :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="showModelThis = false"
  >
    <el-card style="margin-top: -20px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form
            ref="ruleForm"
            :model="ruleForm"
            status-icon
            :size="'mini'"
            :rules="rulesThis"
            label-width="80px"
            class="demo-ruleForm"
          >
            <el-row style="margin-bottom:20px">
              <el-col :span="24">
                <el-form-item label="真实姓名" prop="nickname">
                  <el-input
                    v-model="ruleForm.nickname"
                    :placeholder="'真实姓名'"
                    :disabled="isDetail"
                    maxlength="100"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="手机号" prop="mobile">
                  <el-input
                    v-model="ruleForm.mobile"
                    :placeholder="'手机号'"
                    maxlength="11"
                    :disabled="isDetail"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="角色">
                  <el-radio-group v-model="ruleForm.roleid" :disabled="isDetail">
                    <el-radio v-for="role in rolelist" :key="role.id" :label="role.id">{{ role.role_name }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>

        <el-col :span="6" class="bottom-btn">
          <el-button
            v-if="!isDetail"
            type="primary"
            :size="'mini'"
            @click="submitForm"
          >保 存
          </el-button>
          <el-button :size="'mini'" @click="showModelThis = false">{{
            isDetail ? "关 闭" : "取 消"
          }}</el-button>
        </el-col>

      </el-row>
    </el-card>
  </el-dialog>
</template>
<script>
import asyncRequest from '@/apis/service/interest/accountQuery'
import resToken from '@/mixins/resToken'

export default {
  name: 'Account',
  mixins: [resToken],
  props: ['showModel', 'id', 'isDetail', 'sitem'],
  data() {
    return {
      loading: false,
      title: '添加角色',
      organizeList: [],
      showModelThis: this.showModel,
      coptions: [],
      is_mainoptions: [],
      isIndeterminate: false,
      ruleForm: {
        nickname: '',
        mobile: '',
        roleid: '', // 角色id
        account_id: ''
      },
      rolelist: [],
      platformoptions: [],
      rulesThis: this.rules,
      rules: {
        roleid: [
          {
            required: true,
            message: '请选择角色',
            trigger: 'change'
          }
        ]
      }
    }
  },
  watch: {
    showModel: function(val) {
      this.showModelThis = val
      if (val) {
        this.initForm()
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit('cancel')
      }
    }
  },
  methods: {
    itemidChange(e) {
      this.ruleForm.itemid = e
      this.$refs.ruleForm.validateField('itemid')
    },
    async getRoleWithCompany(companyNo) {
      const { data } = await asyncRequest.rolelist({ level: '3', size: 100 })
      this.rolelist = data.list
    },

    async initForm() {
      this.loading = true

      if (this.id === 'add') {
        await this.resetForm()
      } else {
        await this.initData()
      }
      if (this.id === 'add') {
        this.title = '添加角色'
        this.rulesThis = this.rules
      } else {
        if (this.isDetail) {
          this.title = '角色详情'
          this.rulesThis = {}
        } else {
          this.title = '修改角色'
          this.rulesThis = this.rules
        }
      }
      this.loading = false
    },

    async getClist() {
      this.organizeList = []
      const { code, data, message } = await asyncRequest.getClist({
        size: 10000
      })
      if (code === 0) {
        this.organizeList = data
        this.recursion(this.organizeList)
      } else if (code >= 100 && code <= 104) {
        await this.logout()
      } else {
        this.$message.warning(message)
      }
    },

    handleCheckedCitiesChange(value) {
      const checkedCount = value.length
      this.ruleForm.is_all = checkedCount === this.coptions.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.coptions.length
    },

    recursion(list) {
      list.map((v) => {
        if (v && Array.isArray(v.child)) {
          v.value = v.id + ''
          v.label = v.name
          if (v.child.length === 0) {
            delete v['child']
          } else {
            this.recursion(v.child)
          }
        }
        return v
      })
    },
    async initData() {
      const {
        roleid,
        companyCode,
        nickname,
        mobile,
        id
      } = this.sitem

      const data = {
        roleid,
        companyCode,
        nickname,
        mobile,
        id
      }
      await this.getRoleWithCompany(data.companyCode)
      await this.resetForm(data)
    },
    async resetForm(sitem) {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields()
          this.$refs.ruleForm.clearValidate()
          if (sitem) {
            const {
              companyCode,
              nickname,
              mobile,
              roleid,
              id
            } = sitem

            this.ruleForm = {
              companyCode, nickname, mobile, roleid, id
            }
          } else {
            this.ruleForm = {
              companyCode: '',
              mobile: '',
              roleid: '' // 角色id
            }
          }
        }
      })
    },

    async submitForm() {
      await this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          if (!this.loading) {
            this.loading = true
            const {
              id,
              roleid,
              companyCode
            } = JSON.parse(JSON.stringify(this.ruleForm))

            const model = {
              id,
              roleid,
              companyNo: companyCode
            }

            let res = {}
            if (this.id === 'add') {
              delete model['id']
              res = await asyncRequest.add(model)
            } else {
              res = await asyncRequest.update(model)
            }
            this.loading = false
            if (res && res.code === 0) {
              const title = this.id === 'add' ? '添加成功' : '修改成功'
              this.$notify.success({
                title,
                message: ''
              })
              this.showModelThis = false
              // 刷新
              this.$emit('refresh')
            } else if (res && res.code >= 100 && res.code <= 104) {
              await this.logout()
            } else {
              this.$message.warning(res.message)
            }
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.account {
  .bottom-btn {
    position: absolute;
    bottom: 0px;
    right: 0;
    text-align: right;
    z-index: 2;
  }
}
</style>
