<template>
  <a-form @submit="handleSubmit" :form="form">
    <a-form-item v-show="false" >
      <a-input v-decorator="['deptId']" type="hidden"/>
    </a-form-item>
    <a-form-item v-show="false" >
      <a-input v-decorator="['parentId']" type="hidden"/>
    </a-form-item>
    <a-form-item
      label="父部门"
      :labelCol="{lg: {span: 7}, sm: {span: 7}}"
      :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
      <a-input
        v-decorator="['parentName']"
        disabled/>
    </a-form-item>
    <a-form-item
      label="名称"
      :required="true"
      :labelCol="{lg: {span: 7}, sm: {span: 7}}"
      :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
      <a-input
        v-decorator="[
          'name',
          {rules: [{ required: true, message: '请输入标识' }]}
        ]" />
    </a-form-item>
    <a-form-item
      label="部门性质"
      :labelCol="{lg: {span: 7}, sm: {span: 7}}"
      :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
    >
      <a-select
        v-decorator="['nature', {initialValue: DictCache.VALUE.SYS_DEPT_NATURE.DEFAULT, rules: [{required: true, message: '部门性质不能为空'}]}]"
        @change="changeNature"
        placeholder="请选择">
        <a-select-option
          v-for="(label,value) in natureMap"
          :key="value"
          :label="label"
          :value="value">{{ label }}
        </a-select-option>
      </a-select>
    </a-form-item>

    <a-form-item
      label="部门标识"
      :labelCol="{lg: {span: 7}, sm: {span: 7}}"
      :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
    >
      <a-select
        v-decorator="['code', {initialValue: DictCache.VALUE.SYS_DEPT_CODE.DEFAULT, rules: [{required: true, message: '部门标识不能为空'}]}]"
        @change="changeCode"
        placeholder="请选择">
        <a-select-option
          v-for="(label,value) in codeMap"
          :key="value"
          :label="label"
          :value="value">{{ label }}
        </a-select-option>
      </a-select>
    </a-form-item>

    <a-form-item
      label="类型"
      :labelCol="{lg: {span: 7}, sm: {span: 7}}"
      :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
      :required="true"
    >
      <a-radio-group
        :defaultValue="2"
        v-model="type">
        <a-radio :value="1">公司</a-radio>
        <a-radio :value="2">职能部门</a-radio>
      </a-radio-group>
    </a-form-item>

    <a-form-item
      label="维修负责人"
      :labelCol="{lg: {span: 7}, sm: {span: 7}}"
      :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
    >
      <a-select
        v-decorator="['repairUserIds']"
        mode="multiple">
        <a-select-option
          v-for="item in repairUserList"
          :key="item.userId"
          :label="item.realName"
          :value="item.userId">{{ item.realName }}</a-select-option>
      </a-select>
    </a-form-item>

    <a-form-item
      label="币种"
      :labelCol="{lg: {span: 7}, sm: {span: 7}}"
      :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
    >
      <a-select
        v-decorator="['moneyType']"
        placeholder="请选择">
        <a-select-option
          v-for="(label,value) in moneyTypeMap"
          :key="value"
          :label="label"
          :value="parseInt(value)">{{ label }}
        </a-select-option>
      </a-select>
    </a-form-item>

<!--    <a-form-item-->
<!--      label="汇率"-->
<!--      :labelCol="{lg: {span: 7}, sm: {span: 7}}"-->
<!--      :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"-->
<!--    >-->
<!--      <a-input-number-->
<!--        style="width: 100%"-->
<!--        :min="0"-->
<!--        :step="0.01"-->
<!--        v-decorator="['exchangeRate']"/>-->
<!--    </a-form-item>-->

    <a-form-item
      label="国家/项目代码"
      :labelCol="{lg: {span: 7}, sm: {span: 7}}"
      :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
    >
      <a-input
        v-decorator="['countryCode']"/>
    </a-form-item>

    <a-form-item
      label="是否开启"
      :labelCol="{lg: {span: 7}, sm: {span: 7}}"
      :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
      <a-switch :checked="!closeDept" @change="handleCloseDeptChange" />
    </a-form-item>

    <a-form-item
      label="排序"
      :labelCol="{lg: {span: 7}, sm: {span: 7}}"
      :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
      <a-input
        v-decorator="[
          'sort'
        ]"
        type="number" />
    </a-form-item>
    <a-form-item
      :wrapperCol="{ span: 24 }"
      style="text-align: center"
    >
      <a-button htmlType="submit" :loading="loading" type="primary">提交</a-button>
    </a-form-item>
  </a-form>
</template>

<script>
import pick from 'lodash.pick'
import { queryUsersByParentDeptNatureAll } from '@/api/upms/user'
import { addDept, updateDept } from '@/api/upms/dept'
import { querySysConfig } from '@/api/upms/config'
export default {
  name: 'BaseDept',
  data () {
    return {
      loading: false,
      hiddenHeaderContent: false,
      type: 2,
      codeMap: {},
      natureMap: {},
      moneyTypeMap: {},
      rateMap: {},
      repairUserList: [],
      closeDept: false,
      form: this.$form.createForm(this),
      mustSelectRepairUser: false
    }
  },
  props: {
    dept: {
      type: Object,
      default: () => ({})
    }
  },
  created () {
    // 下拉框map
    this.codeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SYS_DEPT_CODE)
    // 下拉框map
    this.natureMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SYS_DEPT_NATURE)
    this.moneyTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.MONEY_TYPE)
    const rateMap = {}
    // querySysConfig({}).then(res => {
    //   res.data.forEach((item) => {
    //     rateMap[item.code] = item.content
    //   })
    //   this.rateMap = rateMap
    // })
    // 管理者类型
  },
  watch: {
    dept (newV, oldV) { // watch监听props里status的变化，然后执行操作
      this.form.resetFields()
      Object.assign(this.dept, newV)
      this.getRepairUserList({ deptId: newV.deptId, parentId: newV.parentId })
      this.$nextTick(() => {
        this.closeDept = this.dept.closeDept
        if (this.BaseTool.String.isNotBlank(this.dept.nature) && this.BaseTool.String.isNotBlank(this.dept.code) &&
          this.dept.nature === this.DictCache.VALUE.SYS_DEPT_NATURE.BAN_ZU && this.dept.code !== this.DictCache.VALUE.SYS_DEPT_CODE.XIAN_CHANG_WEI_XIU_ZU
        ) {
          this.mustSelectRepairUser = true
        } else {
          this.mustSelectRepairUser = false
        }
        this.form.setFieldsValue(pick(this.dept, ['deptId', 'countryCode', 'parentId', 'parentName', 'name', 'sort', 'code', 'nature', 'moneyType', 'exchangeRate']))
        this.type = this.dept.type
      })
    }
  },
  methods: {
    handleCloseDeptChange () {
      this.closeDept = !this.closeDept
    },
    // changeMoneyType (value) {
    //   const { form: { setFieldsValue } } = this
    //   setFieldsValue({
    //     exchangeRate: this.rateMap[this.DictCache.TYPE.MONEY_TYPE + value]
    //   })
    // },
    getRepairUserList (parameter) {
      const params = {}
      if (this.BaseTool.Object.isBlank(parameter.deptId)) {
        params.deptId = parameter.parentId
      } else {
        params.deptId = parameter.deptId
      }
      params.nature = this.DictCache.VALUE.SYS_DEPT_NATURE.XIANG_MU_BU
      params.code = this.DictCache.VALUE.SYS_DEPT_CODE.XIAN_CHANG_WEI_XIU_ZU
      queryUsersByParentDeptNatureAll(params).then(res => {
        this.repairUserList = res.data
        if (this.BaseTool.Object.isNotBlank(this.dept) && this.BaseTool.Object.isNotBlank(this.dept.repairUserIds)) {
          console.log(1111, this.dept.repairUserIds)
          this.form.setFieldsValue(pick(this.dept, ['repairUserIds']))
        }
      })
    },
    changeMustSelectRepairUser (newCode = null, newNature = null) {
      const { form: { getFieldValue } } = this
      let code = null
      if (this.BaseTool.String.isNotBlank(newCode)) {
        code = newCode
      } else {
        code = getFieldValue('code')
      }

      let nature = null
      if (this.BaseTool.String.isNotBlank(newNature)) {
        nature = newNature
      } else {
        nature = getFieldValue('nature')
      }
      console.log(1111, code, nature)
      if (this.BaseTool.String.isNotBlank(nature) && this.BaseTool.String.isNotBlank(code) &&
        nature === this.DictCache.VALUE.SYS_DEPT_NATURE.BAN_ZU && code !== this.DictCache.VALUE.SYS_DEPT_CODE.XIAN_CHANG_WEI_XIU_ZU
      ) {
        this.mustSelectRepairUser = true
      } else {
        this.mustSelectRepairUser = false
      }
    },
    changeCode (val) {
      this.changeMustSelectRepairUser(val, null)
    },
    changeNature (val) {
      this.changeMustSelectRepairUser(null, val)
    },
    handleSubmit (e) {
      e.preventDefault()
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
        if (!errors) {
          this.loading = true
          const deptId = values.deptId
          values = {
            ...values,
            type: this.type,
            closeDept: this.closeDept
          }
          if (deptId) {
            updateDept(values)
              .then(() => {
                setTimeout(() => {
                  this.loading = false
                  this.$message.info(`提示：修改成功 `)
                  this.$emit('ok', values)
                }, 1500)
              }).catch(() => {
                this.loading = false
              })
          } else {
            addDept(values)
              .then(() => {
                setTimeout(() => {
                  this.loading = false
                  this.$message.info(`提示：添加成功 `)
                  this.$emit('ok', values)
                }, 1500)
              }).catch(() => {
                this.loading = false
              })
          }
        }
      })
    }
  }
}
</script>
