<template>
  <el-dialog
    v-loading="loading"
    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="handleClose"
  >
    <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="rules"
            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="业务公司" required>
                  <search-work-company
                    :value="companyNo"
                    :placeholder="'业务公司'"
                    :size="'mini'"
                    @searchChange="companyNosearchChange"
                  />
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item v-loading="departLoading" label="部门" prop="itemid">
                  <el-cascader
                    v-model="ruleForm.itemid"
                    :disabled="!companyNo"
                    style="width: 100%"
                    :options="departData"
                    :props="{value:'id',label:'name',children:'child',expandTrigger:'hover'}"
                    placeholder="请选择部门"
                    @change="handleDepartChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
        <el-col :span="6" class="bottom-btn">
          <el-button
            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/account'
import companyHelper from '@/mixins/companyHelper'
import resToken from '@/mixins/resToken'

export default {
  name: 'Account',
  mixins: [resToken, companyHelper],
  props: ['showModel', 'id', 'isDetail', 'sitem'],
  data() {
    return {
      companyNo: '',
      roleList: [],
      loading: false,
      title: '添加账号',
      organizeList: [],
      showModelThis: this.showModel,
      coptions: [],
      companyList: [],
      is_mainoptions: [],
      isIndeterminate: false,
      inital: true,
      departData: [],
      itemlist: [],
      ruleForm: {
        nickname: '', // 真实姓名
        mobile: '', // 手机号
        itemid: [], // 角色id
        company_relaton: []
      },
      platformoptions: [],
      rulesThis: this.rules,
      rules: {
        itemid: [
          {
            type: 'array',
            required: true,
            message: '请选择部门',
            trigger: 'change'
          }
        ]
      }
    }
  },
  watch: {
    showModel: function(val) {
      this.showModelThis = val
      if (val) {
        this.initForm()
        // this.initDepartData()
      }
    },
    showModelThis(val) {
      if (!val) {
        this.$emit('cancel')
      }
    },
    companyNo() {
      this.ruleForm.itemid = []
      if (!this.companyNo) return
      this.initDepartData()
    }
  },
  methods: {
    handleClose() {
      this.showModelThis = false
      this.companyNo = ''
      this.inital = true
      this.itemlist = []
    },
    handleDepartChange() {
      this.$nextTick(() => this.$refs.ruleForm.validateField('itemid'))
    },
    async initForm() {
      this.loading = true

      if (this.id === 'add') {
        await this.resetForm()
      } else {
        await this.initData()
      }
      if (this.id === 'add') {
        this.rulesThis = this.rules
      }
      this.loading = false
    },

    async initDepartData() {
      if (this.departLoading) return

      this.departLoading = true
      const { data } = await asyncRequest.depart({ companyNo: this.companyNo })

      this.departLoading = false

      if (data.length === 0) return (this.departData = [])

      const dfs = (data) => {
        data.forEach(item => {
          if (item.child) dfs(item.child)
          if (item.child && item.child.length === 0) delete item.child
        })
      }

      dfs(data[0].child)
      this.departData = data[0].child

      if (this.inital) {
        this.inital = false
        this.ruleForm.itemid = this.itemlist ? this.itemlist.map(({ id }) => id) : []
      }
    },

    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
    },
    async companyNosearchChange(e) {
      const { code } = e
      this.companyNo = code || ''
    },
    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 getRole() {
      const model = {
        status: '', // 状态
        level: '', // 姓名
        role_name: ''
      }
      const res = await asyncRequest.getRole(model)
      if (res && res.code === 0 && res.data) {
        this.roleList = res.data
        this.roleList.map((v1) => {
          v1.id += ''
          v1.status += ''
          return v1
        })
      }
    },
    async initData() {
      const { code, data, message } = await asyncRequest.detail({
        id: this.id
      })
      if (code === 0) {
        await this.resetForm(data)
      } else if (code >= 100 && code <= 104) {
        await this.logout()
      } else {
        this.$message.warning(message)
      }
    },
    async resetForm(sitem) {
      // 重置
      await this.$nextTick(() => {
        if (this.$refs.ruleForm) {
          this.$refs.ruleForm.resetFields()
          this.$refs.ruleForm.clearValidate()

          if (sitem) {
            const {
              item_companyNo,
              item_list,
              nickname,
              mobile,
              id
            } = sitem

            this.itemlist = item_list
            this.companyList = sitem.company_relaton
            this.companyNo = item_companyNo || this.companyList[0].companyCode

            this.ruleForm = {
              id,
              mobile: mobile || '',
              nickname: nickname || ''
            }
          }
        }
      })
    },
    async submitForm() {
      await this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          if (!this.loading) {
            this.loading = true
            const {
              nickname,
              mobile,
              itemid,
              id
            } = JSON.parse(JSON.stringify(this.ruleForm))

            const model = {
              nickname,
              mobile,
              itemid: itemid[itemid.length - 1],
              id
            }

            const 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>
