<template>
  <a-modal
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    :maskClosable="false"
    cancelText="关闭">
    <template slot="title">
      <div class="modalTitle">
        <div class="modalColor"></div>
        <div>{{title}}</div>
      </div>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form-model ref="form" :model="model" :rules="validatorRules" :hideRequiredMark="true">
        <a-row>
          <a-col :span="12">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="所属区划"
              prop="areaName"
              :hidden="false"
            >
              <a-input id="areaName" placeholder="" v-model="model.areaName" :disabled="true"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="上级组织机构"
              prop="parentName"
              :hidden="false"
            >
              <a-input id="parentName" placeholder="" v-model="model.parentName" :disabled="true"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="名称"
              prop="departName"
              :hidden="false"
               >
              <a-input id="departName" placeholder="请输入组织机构名称" v-model="model.departName" :disabled="disableSubmit"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="简称"
              prop="departSimpleName"
              :hidden="false"
            >
              <a-input id="departSimpleName" placeholder="请输入组织机构简称" v-model="model.departSimpleName" :disabled="disableSubmit"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="统一社会信用代码"
              prop="socialCreditCode">
              <a-input placeholder="请输入统一社会信用代码" v-model="model.socialCreditCode" :disabled="disableSubmit"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="⾏使层级" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="performLevel">
              <!-- <j-dict-select-tag  v-model="model.performLevel"  placeholder="请选择行使层级" dictCode="perform_level"/> -->
              <a-select v-model="model.performLevel" placeholder="请选择组织机构⾏使层级" mode="multiple" :disabled="disableSubmit"  :getPopupContainer="(triggerNode) => triggerNode.parentNode">
                <a-select-option
                  v-for="item in performLevelOptions"
                  :key="item.value"
                  :value="item.value">
                  {{ item.title }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="是否垂管">
              <j-dict-select-tag
                v-model="model.manubrium"
                placeholder="请选择是否垂管"
                type="radio"
                dictCode="yn"
                :disabled="disableSubmit"/>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="是否法人单位"
              prop="isLegalDept"
              >
              <j-dict-select-tag
                v-model="model.isLegalDept"
                placeholder="请选择是否法人单位"
                type="radio"
                dictCode="yn"/>
            </a-form-model-item>
          </a-col> -->
          <a-col :span="24" class="aColUn">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="description"
              label="描述">
              <a-textarea placeholder="请输入描述" v-model="model.description" :rows="4" resize="none" :disabled="disableSubmit"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="顺序" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="departOrder">
                  <a-input-number :min="0" :max="99999" v-model="model.departOrder" :disabled="disableSubmit"> </a-input-number>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-col>
          <!-- <a-col :span="24" class="aColUn">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="组织机构类型"
              prop="orgType"
              >
              <j-dict-select-tag
                v-model="model.orgType"
                placeholder="请选择组织机构类型"
                type="radio"
                dictCode="org_type"/>
            </a-form-model-item>
          </a-col> -->
          
          <a-col :span="12" v-show="isEditOrAdd == 'edit'">
            <a-form-model-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="status">
              <!-- <j-dict-select-tag type="list" v-model="model.status"  placeholder="请选择组织机构状态" dictCode="area_status"/> -->
              <a-select v-model="model.status" placeholder="请选择组织机构状态" :disabled="disableSubmit" @change="statusChange"  :getPopupContainer="(triggerNode) => triggerNode.parentNode">
                <a-select-option
                  v-for="item in orgStatusOptions"
                  :key="item.value"
                  :value="item.value">
                  {{ item.title }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="部门编码">
              <a-input v-model="model.departCode" placeholder="请输⼊部⻔编码" :disabled="disableSubmit"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-col :span="12">
              <a-form-model-item label="创建人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createBy">
                <a-input v-model="model.createBy" :disabled="true"> </a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="创建时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                <a-input v-model="model.createTime" :disabled="true"> </a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="最近更新人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="updateBy">
                <a-input v-model="model.updateBy" :disabled="true"> </a-input>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="最近更新时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="updateTime">
                <a-input v-model="model.updateTime" :disabled="true"> </a-input>
              </a-form-model-item>
            </a-col>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
  import { httpAction } from '@/api/manage'
  import { queryIdTree } from '@/api/api'
  import { matchDepartCode } from '@/config/common'
  import pick from 'lodash.pick'
  import ATextarea from 'ant-design-vue/es/input/TextArea'
  import {initDictOptions} from '@/components/dict/JDictSelectUtil'
  export default {
    name: "SysDepartModal",
    components: { ATextarea },
    data () {
      return {
        width:1200,
        departTree:[],
        orgTypeData:[],
        phoneWarning:'',
        departName:"",
        title:"操作",
        seen:false,
        visible: false,
        condition:true,
        disableSubmit:false,
        model: {
          departOrder:0,
          orgCategory:'1'
        },
        menuhidden:false,
        menuusing:true,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },

        confirmLoading: false,
        validatorRules:{
          departName:[{ required: true,validator:this.departNameValidator }],
          departSimpleName:[{ required:true,validator:this.departSimpleNameValidator }],
          socialCreditCode:[{required: true,validator:this.socialCreditCodeValidator}],
          orgType:[{required:true,message:"请选择组织机构类型"}],
          performLevel:[{ required:true,message:"请选择行使层级" }],
          isLegalDept:[{required:true,message:"请选择是否法人单位"}],
          orgCode:[{ required: true, message: '请输入机构编码!' }],
          areaLevel:[{required: true,validator:this.validateAreaLevel}],
          mobile: [{validator:this.validateMobile}],
          orgCategory:[{required: true, message: '请输入机构类型!'}],
          departOrder:[
            {
              required:true,
              message:"请输入组织机构顺序"
            }
          ]
        },
        url: {
          add: "/sys/sysDepart/add",
          edit:"/sys/sysDepart/edit"
        },
        dictDisabled:true,
        // 部门所在层级数组
        areaLevelArr:this.DICTIONARY.areaLevelRadio,
        // 判断新增子节点还是编辑,edit表示编辑,add表示新增自己点
        // 判断是新增还是编辑,add新增，edit是编辑,addCurrent表示新增本级
        isEditOrAdd:'add',
        // 行使层级
        performLevelOptions:[],
        // 组织机构状态
        orgStatusOptions:[],
      }
    },
    created () {
      let _this = this;
      _this.initPerformLevelOptionsDictConfig('perform_level');
      _this.initOrgStatusOptionsDictConfig('orga_type')
    },
    methods: {
      // 初始化行使层级
      initPerformLevelOptionsDictConfig(type){
        let _this = this;
        //初始化字典 - 行政区划类型
        initDictOptions(type).then((res) => {
          if (res.success) {
            let result = [];
            res.result.forEach(item => {
              item['value'] = Number(item['value']);
              if(item['value'] != "1"){
                result.push(item)
              }
            });
            _this.performLevelOptions = result;
          }
        });
      },
      initOrgStatusOptionsDictConfig(type){
        let _this = this;
        //初始化字典 - 行政区划类型
        initDictOptions(type).then((res) => {
          if (res.success) {
            _this.orgStatusOptions = res.result;
          }
        });
      },
      loadTreeData(){
        var that = this;
        queryIdTree().then((res)=>{
          if(res.success){
            that.departTree = [];
            for (let i = 0; i < res.result.length; i++) {
              let temp = res.result[i];
              that.departTree.push(temp);
            }
          }
        })
      },
      add (record) {
        // if(depart){
        //   this.seen = false;
        //   this.dictDisabled = false;
        // }else{
        //   this.seen = true;
        //   this.dictDisabled = true;
        // }
        // this.edit(depart);
        this.visible = true;
        this.model = JSON.parse(JSON.stringify({}));
        this.model.parentId = "0";
        this.model.areaId = record.id;
        this.model.manubrium = "0";
        // this.model.isLegalDept = 1;
        // this.$forceUpdate();
      },
      edit (record) {
          this.visible = true;
          // this.loadTreeData();
          // this.model.parentId = record!=null?record.toString():null;
          // if(this.seen){
          //   this.model.orgCategory = '1';
          // }else{
          //   this.model.orgCategory = '2';
          // }
          // console.log(record);
          this.model = JSON.parse(JSON.stringify(record));
          if(JSON.parse(this.model.performLevel) == null){
            this.model.performLevel = [];
          }else{
            this.model.performLevel = JSON.parse(this.model.performLevel);
          }
          this.isEditOrAdd = 'edit';
          this.$forceUpdate();
      },
      check(record){
        this.visible = true;
        // this.loadTreeData();
        // this.model.parentId = record!=null?record.toString():null;
        // if(this.seen){
        //   this.model.orgCategory = '1';
        // }else{
        //   this.model.orgCategory = '2';
        // }
        // console.log(record);
        this.model = JSON.parse(JSON.stringify(record));
        this.model.performLevel = JSON.parse(this.model.performLevel);
        if(!this.model.description){
          this.model.description = " ";
        };
        if(!this.model.departCode){
          this.model.departCode = " ";
        }
        this.isEditOrAdd = 'check';
        this.$forceUpdate();
      },
      addChildNode(record,districtRecord){
          this.visible = true;
          console.log(record);
          this.modelCurrent = {};
          // this.model = JSON.parse(JSON.stringify({}));
          this.modelCurrent.parentId = record.id;
          this.modelCurrent.areaId = districtRecord.id;
          this.modelCurrent.areaName = record.areaName;
          this.modelCurrent.parentName = record.departName;
          this.modelCurrent.manubrium = "0";
          this.modelCurrent.status = '1';
          this.isEditOrAdd = 'add';
          this.modelCurrent.orgType = "1";
          this.modelCurrent.isLegalDept = "1";
          this.model = this.modelCurrent;
          console.log(this.model)
      },
      addCurrentNode(treeRow){
          this.visible = true;
          this.modelCurrent = {};
          this.isEditOrAdd = 'add';
          this.modelCurrent.orgType = "1";
          this.modelCurrent.isLegalDept = "1";
          this.modelCurrent.status = '1';
          this.modelCurrent.areaId = treeRow.id;
          this.modelCurrent.areaName = treeRow.areaName;
          this.modelCurrent.manubrium = "0";
          this.model = this.modelCurrent;
          this.isEditOrAdd = 'addCurrent';
          this.$forceUpdate();
      },
      close () {
        this.$emit('closeModel');
        this.disableSubmit = false;
        this.visible = false;
        this.$refs.form.resetFields();
      },
      statusChange(value){
        let _this = this;
        if(value == '0'){
          console.log(value);
          this.$confirm({
            class:"delete_qx",
            title: '警告',
            content: (
              <div>
                <div><span style="color:red">您将组织机构状态修改为“无效”</span>，系统会默认将下属组织机构、用户都修改为“无效”状态，“无效”的用户无法登录。</div>
              </div>
            ),
            okText: '确定',
            icon:"exclamation-circle",
            onOk(){
              _this.model.status = "0";
              // _this.handleOk();
            }, 
            onCancel(){
              _this.model.status = "1";
            }
          });
        }
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        if(that.isEditOrAdd == 'add'){
          that.model.status = '1'
        }
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            that.model.performLevel = JSON.stringify(that.model.performLevel);
            if(that.isEditOrAdd == 'check'){
              that.close();
              that.confirmLoading = false;
            }else if(that.isEditOrAdd == 'add'){
              httpAction(this.url.add,this.model,"post").then((res)=>{
                if(res.success){
                  that.$message.success(res.message);
                  // that.loadTreeData();
                  // that.$emit('ok');
                  that.close();
                  that.$emit('reloadTableData')
                }else if(res.code == "17003"){
                  this.$confirm({
                    class:"delete_qx",
                    title: '注意',
                    content: (
                      <div>
                        <div>{res.message}</div>
                      </div>
                    ),
                    okText: '确定', 
                    type:"error",
                    icon:"close-circle"
                  });
                }else if(res.code == "17005"){
                  this.$confirm({
                    class:"delete_qx",
                    title: '注意',
                    content: (
                      <div>
                        <div>{res.message}</div>
                      </div>
                    ),
                    okText: '确定', 
                    type:"error",
                    icon:"close-circle"
                  });
                }else{
                  that.$message.warning(res.message);
                };
              }).finally(() => {
                that.confirmLoading = false;
                that.model.performLevel = JSON.parse(that.model.performLevel);
                // that.close();
              })
            }else if(that.isEditOrAdd == 'edit'){
              httpAction(this.url.edit,this.model,"put").then((res)=>{
                if(res.success){
                  that.$message.success(res.message);
                  that.$emit('reloadTableData');
                  that.close();
                }else if(res.code == "17003"){
                  this.$confirm({
                    class:"delete_qx",
                    title: '注意',
                    content: (
                      <div>
                        <div>{res.message}</div>
                      </div>
                    ),
                    okText: '确定', 
                    type:"error",
                    icon:"close-circle"
                  });
                }else if(res.code == "17005"){
                  this.$confirm({
                    class:"delete_qx",
                    title: '注意',
                    content: (
                      <div>
                        <div>{res.message}</div>
                      </div>
                    ),
                    okText: '确定', 
                    type:"error",
                    icon:"close-circle"
                  });
                }else{
                  that.$message.warning(res.message);
                }
              }).finally(() => {
                that.confirmLoading = false;
                that.model.performLevel = JSON.parse(that.model.performLevel);
              })
            }else if(that.isEditOrAdd == 'addCurrent'){
              httpAction(this.url.add,this.model,"post").then((res)=>{
                if(res.success){
                  that.$message.success(res.message);
                  // that.loadTreeData();
                  // that.$emit('ok');
                  that.$emit('reloadTableData');
                  that.close();
                }else if(res.code == "17003"){
                  this.$confirm({
                    class:"delete_qx",
                    title: '注意',
                    content: (
                      <div>
                        <div>{res.message}</div>
                      </div>
                    ),
                    okText: '确定', 
                    type:"error",
                    icon:"close-circle"
                  });
                }else if(res.code == "17005"){
                  this.$confirm({
                    class:"delete_qx",
                    title: '注意',
                    content: (
                      <div>
                        <div>{res.message}</div>
                      </div>
                    ),
                    okText: '确定', 
                    type:"error",
                    icon:"close-circle"
                  });
                }else{
                  that.$message.warning(res.message);
                }
              }).finally(() => {
                that.confirmLoading = false;
                that.model.performLevel = JSON.parse(that.model.performLevel);
              })
            }
          }else{
            return false;
          }
        })
      },
      handleCancel () {
        this.close()
      },
      validateMobile(rule,value,callback){
        if (!value || new RegExp(/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/).test(value)){
          callback();
        }else{
          callback(new Error('您的手机号码格式不正确'));
        }
      },
      // 机构组织名称
      departNameValidator(rule,value,callback){
        let _this = this;
        if(!value || value.trim() == ""){
          callback(new Error('请输入机构组织名称'))
        }else{
          _this.model.departName = value.trim();
          callback();
        }
      },
      // 机构组织简称
      departSimpleNameValidator(rule,value,callback){
        let _this = this;
        if(!value || value.trim() == ""){
          callback(new Error('请输入机构组织简称'))
        }else{
          _this.model.departSimpleName = value.trim();
          callback();
        }
      },
      // 统一社会信用代码
      socialCreditCodeValidator(rule,value,callback){
        let _this = this;
        if(!value || value.trim() == ""){
          callback(new Error('请输入统一社会信用代码'))
        }else if(matchDepartCode(value.trim()) != 4){
          callback(new Error('统一社会信用代码有误，请检查'))
        }else{
          _this.model.socialCreditCode = value.trim();
          callback();
        }
      },
      // 部门所在层级
      validateAreaLevel(rule,value,callback){
        if(!value){
          callback(new Error('请选择部门所在层级'));
        }else{
          callback();
        }
      }
    },
  }
</script>

<style lang="less" scoped>
/deep/.ant-tabs-nav .ant-tabs-tab-active {
  
}
/deep/.ant-tabs-ink-bar{
  background-color:#4717f6;
}
/deep/.action-button .ant-btn-primary{
  
  
  border-radius: 2px;
}
/deep/ .ant-modal-footer {
  padding: 10px 16px 45px;
  border-top: 0;
  >div{
    display: flex;
    justify-content: center;
  }
  .ant-btn {
    width: 76px;
    height: 35px;
    line-height: 34px;
    border-radius: 2px 2px 2px 2px;
    opacity: 1;
    
    padding: 0;

 
  }

  .ant-btn-primary {
    
    
    color: #ffffff;

    &:hover {
      color: #fff !important;
    }
  }
}


// 输入框
/deep/.ant-input {
  height: 38px;
}
/deep/ textarea.ant-input {
  height: auto;
}
/deep/.input-table .tbody .td input {
  height: 38px;
}
// 下拉框
::v-deep.ant-select {
  .ant-select-selection--single {
    height: 38px;
  }
  .ant-select-selection__rendered {
      line-height: 38px;
    }
  .ant-select-dropdown-menu-item-active:not(.ant-select-dropdown-menu-item-disabled) {
    
  }
}
/deep/.ant-input-number{
  height: 38px;
  line-height: 38px;
}
/deep/.ant-select-dropdown.ant-select-dropdown--multiple .ant-select-dropdown-menu-item-selected .ant-select-selected-icon {
  
}
::v-deep.ant-row{
&>.ant-col:nth-child(3),&>.ant-col:nth-child(4),&>.ant-col:nth-child(5),&>.ant-col:nth-child(6) {
  .ant-form-item {
    .ant-form-item-control-wrapper {
      position: relative;

      &::before {
        position: absolute;
        content: '*';
        color: #f10f0f;
        top: 0;
        right: -24px;
        font-size: 24px;
        line-height: 44px;
      }
    }
  }
}
}
// 滚动条
/deep/::-webkit-scrollbar-thumb {
  
  border-radius: 9px 9px 9px 9px;
}
</style>
<style scoped>
  .aColUn > div >>> .ant-col:first-child{
    width: 15.50%;
  }
  .aColUn > div >>> .ant-col:nth-child(2){
    width: 84.50%;
  }
  .aColUn > div >>> .ant-col:nth-child(2) > .ant-form-item-control{
    width: 98.55%;
  }
  .ant-form-explain{
      margin-bottom: -1px;
  }
  .ant-form-item-with-help{
      margin-bottom: 5px;
  }
  .ant-col-12 >>> .ant-form-item-label{
    /* background-color: red; */
    width: 30.83333333%;
  }
  .modalColor{
    
  }
</style>
