<template>
  <Modal v-model="showModalUserBinding" :mask-closable="false" :closable="false" :title="modalTitle" :value="value"
         width="820" v-draggable="options">

    <i-form label-position="right" :label-width="100" ref="userBindingForm" :model="bean" :rules="rules" inline>
      <Row>
        <i-col :span="12">
          <Form-item label="绑定类型" prop="bindingType" class="ivu-form-item-search">
            <Select v-model="bean.bindingType" style="width: 243px;" :disabled="disabled">
              <Option :value="'0'" :key="0">区域</Option>
              <Option :value="'1'" :key="1">单位</Option>
              <Option :value="'2'" :key="2">代管</Option>
            </Select>
          </Form-item>
        </i-col>
        <i-col :span="12" v-if="bean.bindingType === '1'">
          <Form-item label="选择单位" class="ivu-form-item-search">
            <!--<Button type="primary" size="small" @click="checkObj" ghost :disabled="disabled">点击选择</Button>-->
            <Select v-model="bean.objId" filterable placeholder="请输入关键字搜索" @on-select="checkedObjOk"
                    style="width:180px;overflow : hidden; white-space: nowrap; " remote
                    :remote-method="remoteMethod1" :loading="loading1" :max-tag-count="1" clearable>
              <Option v-for="item in companys" :value="item.id" :key="item.id">{{ item.companyName }}</Option>
            </Select>
          </Form-item>
        </i-col>
        <i-col :span="12" v-if="bean.bindingType === '0'">
          <Form-item label="选择区域" class="ivu-form-item-search">
            <!--<Button type="primary" size="small" @click="checkObj" ghost :disabled="disabled">点击选择</Button>-->
            <Select v-model="bean.objId" filterable placeholder="请输入关键字搜索" @on-select="checkedObjOk"
              style="width:180px;overflow : hidden; white-space: nowrap; " remote
              :remote-method="remoteMethod1" :loading="loading1" :max-tag-count="1" clearable>
              <Option v-for="item in areas" :value="item.id" :key="item.id">{{ item.areaName }}</Option>
            </Select>
          </Form-item>
        </i-col>
        <i-col :span="12">
          <Form-item label="对象名称" prop="objName" class="ivu-form-item-search">
            <Input v-model="bean.objName" style="width: 243px;" disabled></Input>
          </Form-item>
        </i-col>
        <i-col :span="12">
          <Form-item label="用户名称" prop="userName" class="ivu-form-item-search">
            <Input v-model="bean.userName" style="width: 243px;" disabled></Input>
          </Form-item>
        </i-col>
        <!--<i-col :span="12">
          <Form-item label="关联类型" prop="userType" class="ivu-form-item-search">
            <Select v-model="bean.userType" style="width: 243px;" :disabled="disabled">
              <Option :value="0" :key="0">业务员身份</Option>
              <Option :value="1" :key="1">普通用户身份</Option>
            </Select>
          </Form-item>
        </i-col>-->
        <i-col :span="12">
          <Form-item label="选择系统" class="ivu-form-item-search">
            <Button type="primary" size="small" @click="checkSystem" ghost :disabled="disabled">点击选择</Button>
          </Form-item>
        </i-col>
        <i-col :span="12">
          <Form-item label="系统名称" prop="systemName" class="ivu-form-item-search">
            <Input v-model="bean.systemName" style="width: 243px;" disabled></Input>
          </Form-item>
        </i-col>
        <i-col :span="12">
          <Form-item label="备注" class="ivu-form-item-search">
            <Input v-model="bean.remark" style="width: 243px;" :disabled="disabled"></Input>
          </Form-item>
        </i-col>
      </Row>
    </i-form>
    <div slot="footer">
      <Button @click="cancel">关闭</Button>
      <Button type="primary" :loading="saveLoading" @click="ok('userBindingForm')" v-if="showSaveBtn">保存</Button>
    </div>
    <bc-check ref="checkSystem" :show.sync="checkSystemShow" :treeData="systems" @checkOk="checkedSystemOk" :treeId="'checkSystem'" ></bc-check>
  </Modal>
</template>

<script>
  import { addUserBinding, editUserBinding } from '../../../../api/rbac/userBinding-api'
  import { getSystem } from '../../../../api/rbac/res-manage.js'
  import { getCompanyList } from '../../../../api/base/company-api'
  import { getAreaList } from '../../../../api/base/area-api'

  let $this
  export default {
    name: 'userBindingModal',
    components: {},
    props: {
      show: Boolean,
      value: Object
    },
    data () {
      return {
        loading1: false,
        companys: [],
        areas: [],
        checkSystemShow: false,
        systems: [],
        showModalUserBinding: false,
        bean: {},
        initBean: {bindingType: '1'},
        flag: '',
        saveLoading: false,
        modalTitle: '',
        disabled: false,
        showSaveBtn: true,
        rules: {
          objName: [
            { required: true, message: '绑定对象名称不能为空!', trigger: 'blur' },
          ],
          userName: [
            { required: true, message: '用户名不能为空!', trigger: 'blur' },
          ],
          userType: [
            { required: true, message: '关联类型不能为空!', trigger: 'blur' },
          ],
          systemName: [
            { required: true, message: '关联系统名称不能为空!', trigger: 'blur' },
          ],
          bindingType: [
            { required: true, message: '绑定类型不能为空!', trigger: 'blur' },
          ],
        },
        options: {
          trigger: '.ivu-modal-header',
          body: '.ivu-modal',
          recover: true
        }
      }
    }, methods: {
      ok (name) {
        this.$refs[name].validate((valid) => {
          if (!valid) {
            return
          }//表单校验失败则返回
          this.saveLoading = true
          //this.showModalUserBinding = false;
          if (this.flag == 'edit') {
            let parmas = this.bean
            delete parmas['createTime']
            delete parmas['modifyTime']
            //执行修改操作
            editUserBinding(parmas).then(data => {
              if (!data.status) {
                this.$Message.error(data.error.message)
                this.saveLoading = false
                console.log(data)
                return false
              }
              this.$Message.success('操作成功！')
              this.closeAndRefresh()
            }).catch(err => {
              this.$Message.error('操作失败！')
              this.saveLoading = false
              console.log(err)
            })
          } else if (this.flag == 'add') {
            delete this.bean['createTime']
            delete this.bean['modifyTime']
            //执行添加操作
            addUserBinding(this.bean).then(data => {
              if (!data.status) {
                this.$Message.error(data.error.message)
                this.saveLoading = false
                console.log(data)
                return false
              }
              this.$Message.success('操作成功！')
              this.closeAndRefresh()
            }).catch(err => {
              this.$Message.error('操作失败！')
              this.saveLoading = false
              console.log(err)
            })
          }
        })

      },
      cancel () {
        this.showModalUserBinding = false
        this.$emit('update:show', false)
        //重置校验结果
        this.$refs['userBindingForm'].resetFields()
      },
      closeAndRefresh () {
        this.saveLoading = false
        this.cancel()
        this.$emit('reload-data')
      },
      checkedObjOk (e){//选择对象-完成
        this.bean.objId = e.value
        this.bean.objName = e.label
        this.$forceUpdate();
      },
      checkSystem (){//选择单位或区域
        this.checkSystemShow=true;
        getSystem().then(res => {
          this.systems = res.data.result;
        });
      },
      checkedSystemOk (checkedSystems){//选择角色-完成
        this.bean.systemId = checkedSystems[0].id
        //this.bean.roleCode = checkedRoles[0].code
        this.bean.systemName = checkedSystems[0].name

        this.$forceUpdate();
      },
      remoteMethod1 (query) {
        if (query !== '') {
          this.loading1 = true;
          if (this.bean.bindingType === '1'){
            getCompanyList({companyName__like:query}).then(res => {
              this.companys = res.data.result;
              this.loading1 = false;
            });
          }else if(this.bean.bindingType === '0'){
            getAreaList({areaName__like:query}).then(res => {
              this.areas = res.data.result;
              this.loading1 = false;
            });
          }
        } else {
          this.companys = [];
        }
      },
    },
    mounted () {
      $this = this
      this.bean = this.initBean
    },
    watch: {
      show: {
        immediate: true,
        handler: function () {
          this.showModalUserBinding = this.show
        }
      },
      value: {
        immediate: true,
        handler: function () {
          //赋值
          this.bean = this.value.bean == null ? Object.assign({}, this.initBean) : JSON.parse(JSON.stringify(this.value.bean))
          this.flag = this.value.flag
          this.modalTitle = this.value.title
          //如果时查看的功能，要将所有input框只读，并且去掉保存按钮
          if (this.flag == 'view') {
            this.disabled = true
            this.showSaveBtn = false
          } else {
            this.disabled = false
            this.showSaveBtn = true
          }
        }
      }
    }

  }
</script>

<style scoped>
  .ivu-form-item-search {
    margin-bottom: 21px;
  }
</style>
