<template>
  <a-modal  :width="1000"
            height="auto" :visible="addVisible" @cancel="handleCancelClick"
            cancelText="取消" okText="提交" @ok="handleSubmit">
    <a-form-model
            class="a-form-model"
            ref="ruleForm"
            :model="itemAddData"
            :rules="validateRules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
            @validate="validate">
      <div class="a-form-model-item-view">
        <a-form-model-item has-feedback class="a-form-model-item" label="部门名称" prop="departmentName">
          <a-select
                  show-search
                  :value="itemAddData.departmentName"
                  placeholder="输入或搜索名称"
                  style="width: 200px"
                  :default-active-first-option="false"
                  :show-arrow="false"
                  :filter-option="false"
                  :not-found-content="null"
                  @search="onDepartmentSearch"
                  @change="onDepartmentChange">
            <a-select-option v-for="m in  departmentOption" :key="m.value">{{m.text}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item has-feedback class="a-form-model-item" ref="parentId" label="上级部门" prop="parentId">
          <!--此处代码保留，用作调试-->
          <!--<a-tree-select
                  :allowClear="true"
                  v-model="itemAddData.parentId"
                  :defaultValue="itemAddData.parentId"
                  style="width: 300px"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="treeData"
                  placeholder="请选择上级部门"
                  tree-default-expand-all
                  @change="handleDepartmentChange"
          >
          </a-tree-select>-->
          <a-tree-select
                  v-model="itemAddData.parentId"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                  :tree-data="deptTreeData"
                  placeholder="请选择上级部门"
                  tree-default-expand-all
                  @change="handleDepartmentChange"
          >
          </a-tree-select>
        </a-form-model-item>
      </div>
      <div class="a-form-model-item-view">
        <a-form-model-item has-feedback class="a-form-model-item" ref="orderNum" label="部门排序" prop="orderNum">
          <a-input-number
                  placeholder="请输入部门排序"
                  v-model="itemAddData.orderNum"
                  @blur="
                         () => {
                           $refs.orderNum.onFieldBlur();
                         }"
                  style="width: 200px"
          />
        </a-form-model-item>
      </div>
    </a-form-model>
  </a-modal>
</template>
<script>

const formItemLayout = {
  labelCol: { span: 3 },
  wrapperCol: { span: 18 }
}
import locale from 'ant-design-vue/lib/date-picker/locale/zh_CN'
import Editor from '@/components/editor/Editor'
import store from '@/store'
import baseUtils from '@/utils/baseUtils'
import moment from 'moment'
moment.locale('zh-cn')
export default {
  name: 'ItemAdd',
  components: {
    Editor:Editor,
    moment:moment,
    baseUtils:baseUtils,
    store:store
  },
  //子组件生命props就可以从父组件里面拿到数据
  props: {
    addVisible: {
      default: false
    }
  },
  data () {
    return {
      locale:locale,
      submitUrl:'api/v1/authDepartment/addAuthDepartment', //提交URL
      submitDictUrl:'api/v1/platformDict/addItem', //提交URL
      loading: false,
      formItemLayout,
      form: this.$form.createForm(this),
      itemAddData: {
        departmentName:'',
        parentId:'',
        orderNum:''
      },
      treeData:[
        {
          title: 'Node1',
          value: '0-0',
          key: '0-0',
          children: [
            {
              value: '0-0-1',
              key: '0-0-1',
              scopedSlots: {
                // custom title
                title: 'title',
              },
            },
            {
              title: 'Child Node2',
              value: '0-0-2',
              key: '0-0-2',
            },
          ],
        },
        {
          title: 'Node2',
          value: '0-1',
          key: '0-1',
        },
      ],
      deptTreeData: [],
      departmentOption:[ //需要选择的部门名称

      ],
      businessDictAddData:{},//新增部门的时候需要新增的数据字段
      needAddDict:false, //是否需要生成新的字典
      labelCol: {
        span: 5,
      },
      wrapperCol: {
        span: 15,
      },
      //校验规则
      validateRules: {
        departmentName: [
            { required: true, message: '请输入或者选择部门名称', trigger: 'change' }
          ],
        orderNum: [
          { required: true,pattern: new RegExp(/^[1-9]\d*$/, "g"),  message: '请部门排序且为整数', trigger: 'blur' },
        ],
        parentId: [{ required: false, message: '请选择父级部门', trigger: 'change' }],
        regionId: [{ required: true, message: '请选择地区', trigger: 'change' }],
        type: [
          {
            type: 'array',
            required: true,
            message: 'Please select at least one activity type',
            trigger: 'change',
          },
        ],
      },
    }
  },
  methods: {
    handleDepartmentChange(value){
      console.log('handleDepartmentChange :'+value)
      this.itemAddData.parentId = value
      console.log('this.itemAddData.parentId :'+this.itemAddData.parentId)
    },
    addItem(){
      //生成数据字典
      let data = this.businessDictAddData
      console.log('数据字典数据: '+JSON.stringify(data))
      if(data && data.dictKey){
        this.$postBodyRequest(this.submitDictUrl, {
          ...data
        }).then((r) => {
          console.log('新增数据字典: '+JSON.stringify(r))
        }).catch((err) => {
          this.$message.error('新增数据字典失败:'+JSON.stringify(err))
        })
      }
    },
    returnOptionValue(key,optionList){ //根据key返回选项的值
      let result;
      if(optionList && optionList.length > 0){
        optionList.map(item => {
          if(item.value == key){
            result = item.text
            return;
          }
        })
      }
      return result;
    },
    onDepartmentChange(key){
      let departmentName = this.returnOptionValue(key,this.departmentOption);
      this.itemAddData.departmentName = departmentName
      if(this.needAddDict){
        //生成字典信息
        this.businessDictAddData.dictType = 'departmentDict'
        this.businessDictAddData.dictKey = departmentName
        this.businessDictAddData.dictValue = departmentName
        this.businessDictAddData.dictRemark = departmentName
        this.businessDictAddData.platformDictId = key
      }
      console.log('this.businessDictAddData:'+this.businessDictAddData.length > 0)
      console.log('this.businessDictAddData: '+JSON.stringify(this.businessDictAddData))
      console.log('this.itemAddData.departmentName :'+this.itemAddData.departmentName)
      console.log('onDepartmentChange: '+key)
    },
    onDepartmentSearch(value){
      if(baseUtils.isNull(value)){
        return;
      }
      this.departmentOption.splice(0,this.departmentOption.length)
      this.$get('api/v1/platformDict/queryDictionaryByValue',
              {
                "dictValue":value
              }
      ).then((r) => {
        let data = r.data.data;
        if(data && data.length > 0){
          data.map(item => {
            let option = {
              'text':item.dictValue,
              'value':item.platformDictId
            }
            this.departmentOption.push(option);
          })
          this.businessDictAddData = {}
          this.needAddDict = false
        }else{
          this.$get('api/v1/platform/snowflakeId',).then((r) => {
            let data = r.data.data;
            if(data && data.length > 0){
              let option = {
                  'text':value,
                  'value':data
              }
              this.departmentOption.push(option);
              this.needAddDict = true
            }
          })
        }
      })
      console.log('onDepartmentSearch: '+value)
      console.log('this.departmentOption: '+JSON.stringify(this.departmentOption))
    },
    validate(successStatus,object){
      console.log(successStatus)
      console.log(object)
    },
    handleCancelClick(){
      this.resetForm();
      this.clearAll();
      this.$emit("close")
    },
    clearAll(){
      console.log('clearAll')
      this.resetForm();
    },
    onClose () {
      this.resetForm()
      this.$emit('close')
    },
    resetForm() { //重置表单
      this.loading = false
      this.departmentOption.splice(0,this.departmentOption.length)
      this.businessDictAddData = {}
      this.$refs.ruleForm.resetFields();
    },
    handleSubmit () { //处理提交
      let that = this
      that.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.loading = true
          console.log('新增部门: '+JSON.stringify( this.itemAddData))
          this.$postBodyRequest(this.submitUrl, {
            ...this.itemAddData
          }).then(() => {
            this.resetForm()
            this.$emit('success')
          }).catch(() => {
            this.loading = false
          })
          this.addItem();
          console.log('新增结束 ')
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
  },
  watch: {
    //此处名字必须是这个
    addVisible () {
      if (this.addVisible) {
        this.$get('api/v1/authDepartment/queryAllDepartmentTree').then((r) => {
          this.deptTreeData = r.data.data.children
        })
      }
    }
  }
}
</script>
<style lang="less" scoped>
  /*使用~@引入*/
  @import "~@/utils/utils.less";
</style>
