<template>
  <a-modal  :width="1000"
            height="auto"
            :visible="editVisible" @cancel="handleCancelClick"
            cancelText="取消" okText="提交" @ok="handleSubmit">
    <a-form-model
            class="a-form-model"
            ref="ruleForm"
            :model="itemEditData"
            :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="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
                  v-model="itemEditData.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="orderNum"
                  @blur="
                         () => {
                           $refs.orderNum.onFieldBlur();
                         }"
                  style="width: 200px"
          />
        </a-form-model-item>
      </div>
    </a-form-model>
  </a-modal>
</template>
<script>
  import locale from 'ant-design-vue/es/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')
  const formItemLayout = {
    labelCol: { span: 3 },
    wrapperCol: { span: 18 }
  }
  export default {
    name: 'ItemEdit',
    components: {
      Editor:Editor,
      moment:moment,
      baseUtils:baseUtils
    },
    props: {
      editVisible: {
        default: false
      },
      itemEditData: {
        required: true,
        default: {

        }
      },
    },
    data () {
      return {
        locale:locale,
        deptTreeData: [],
        departmentOption:[ //需要选择的部门名称

        ],
        businessDictAddData:{},//修改部门的时候需要修改的数据字段
        needAddDict:false, //是否需要生成新的字典
        authUserIdOption:[ //当前系统里面的所有用户

        ],
        test:'1',
        departmentName:'', //部门名称 此处必须单独独立设置 否则修改的时候无法显示修改后的值
        orderNum:1, //部门排序 此处必须单独独立设置 否则修改的时候无法显示修改后的值
        submitUrl:'api/v1/authDepartment/updateDepartment', //提交URL
        submitDictUrl:'api/v1/platformDict/addItem', //提交URL
        timeFormat:'YYYY-MM-DD', //时间格式
        beginAndEndTimeFormat:'YYYY-MM', //时间格式
        uploadUrl: process.env.BASE_API+'/api/systemFile/uploadFile', //文件时上传
        //校验规则
        validateRules: {
          departmentName: [
            { required: true, message: '请输入或者选择部门名称', trigger: 'change' }
          ],
          orderNum: [
            { required: true ,message: '请输入部门排序且为整数',trigger: 'blur' },
          ],
          parentId: [
                  { required: false, message: '请选择父级部门', trigger: 'change' },
                  { validator: this.parentIdValidator ,trigger: 'change'},
          ],
          regionId: [{ required: true, message: '请选择地区', trigger: 'change' }],
          type: [
            {
              type: 'array',
              required: true,
              message: 'Please select at least one activity type',
              trigger: 'change',
            },
          ],
          resource: [
            { required: true, message: 'Please select activity resource', trigger: 'change' },
          ],
          desc: [{ required: true, message: 'Please input activity form', trigger: 'blur' }],
        },
        formItemLayout,
        dictDataList:[], //字典数据集合
        //上传文件的时候必须带上的token
        uploadHeader:{
          "Authentication":store.state.account.token
        },
        previewVisible: false,
        previewImage: '',
        labelCol: {
          span: 5,
        },
        wrapperCol: {
          span: 15,
        },
        loading: false,
      }
    },
    methods: {
      parentIdValidator(rule, value, callback){
        console.log('选择的值:'+value)
        console.log('本身的值:'+this.itemEditData.id)
        console.log('是否相等:'+(this.itemEditData.id == value))
        if(baseUtils.isNull(value)) {
          callback(new Error('请选择数据'));
        }
        if(this.itemEditData.id == value){
          callback(new Error('不能选择本身作为上级'));
        }
        callback()
      },
      numberValidator(rule, value, callback){
        console.log(value)
        console.log(baseUtils.isNumberString(value))
        if(baseUtils.isNull(value)) {
          callback(new Error('请输入数据'));
        }
        if(!baseUtils.isNumberString(value)) {
          callback(new Error('请输入数字:'+value));
        }
        callback()
      },
      handleDepartmentChange(value){
        console.log('是否选择了本身: ' + (this.itemEditData.id == value))
        console.log('handleDepartmentChange :'+value)
        this.itemEditData.parentId = value
        console.log('this.itemEditData.parentId :'+this.itemEditData.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);
        console.log('定位到部门名称的数据:'+departmentName)
        //this.itemEditData.departmentName = departmentName
        this.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.itemEditData.departmentName :'+this.itemEditData.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))
      },
      handleAuthUserChange(value){
        this.itemEditData.authUserId = value
      },
      onEndTimeChange(value, dateString){
        console.log('Selected Time: ', value);
        console.log('Formatted Selected Time: ', dateString);
        this.itemEditData.endTime = dateString
      },
      onBeginTimeChange(value, dateString){
        console.log('Selected Time: ', value);
        console.log('Formatted Selected Time: ', dateString);
        this.itemEditData.beginTime = dateString
      },
      onTimeOK(value){
        console.log('onOk: ', value);
      },
      moment, //时间处理
      handleCancel() {
        this.previewVisible = false;
      },
      validate(successStatus,object){
        console.log(successStatus)
        console.log(object)
      },
      resetForm() { //重置表单
        this.$refs.ruleForm.resetFields();
      },
      handleCancelClick(){
        this.reset();
        this.clearAll();
        this.$emit("close")
      },
      reset () {
        this.loading = false
        this.$refs.ruleForm.resetFields();
      },
      onClose () {
        this.reset();
        //清除所有图片内容
        this.clearAll();
        this.$emit('close')
      },
      clearAll(){
        console.log('clearAll')
        //清除所有文件内容
        this.authUserIdOption.splice(0,this.authUserIdOption.length);
        this.departmentOption.splice(0,this.departmentOption.length);
      },
      handleSubmit () { //处理提交
        let that = this
        that.$refs.ruleForm.validate(valid => {
          if (valid) {
            //格式化时间
            /*if(this.itemEditData.beginTime){
              this.itemEditData.beginTime = moment(this.itemEditData.beginTime).format(this.beginAndEndTimeFormat);
            }*/
            console.log('修改部门: '+JSON.stringify(this.itemEditData))
            if(!baseUtils.isNull(this.departmentName)){
              this.itemEditData.departmentName = this.departmentName
            }
          if(!baseUtils.isNull(this.orderNum)){
              this.itemEditData.orderNum = this.orderNum
            }
            this.loading = true
            //从表单里面拿到值
            this.$putBodyRequest(this.submitUrl, {
              ...this.itemEditData
            }).then(() => {
              this.loading = false
              this.resetForm()
              this.clearAll();
              this.reset()
              this.$emit('success')
            }).catch(() => {
              this.$message.error('更新出现错误')
              this.loading = false
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }
    },
    watch: { //监控弹窗的变化
      editVisible () {
        if (this.editVisible) {
          this.departmentName = this.itemEditData.departmentName
          this.orderNum = this.itemEditData.orderNum
          console.log('itemEditData'+JSON.stringify(this.itemEditData))
          this.$get('api/v1/authDepartment/queryAllDepartmentTree').then((r) => {
            this.deptTreeData = r.data.data.children
          })
        }
      }
    }
  }
</script>
<style lang="less" scoped>
  /*使用~@引入*/
  @import "~@/utils/utils.less";
</style>
