<template>
  <div class="app-container calendar-list-container" style="height: 700px;">
    <basic-container>
<!--      <div class="filter-container">-->
<!--        <el-button-group>-->
<!--          <el-button-->
<!--            v-if="deptManager_btn_add"-->
<!--            type="primary"-->
<!--            icon="plus"-->
<!--            @click="handlerAdd">添加-->
<!--          </el-button>-->
<!--          <el-button-->
<!--            v-if="deptManager_btn_edit"-->
<!--            type="primary"-->
<!--            icon="edit"-->
<!--            @click="handlerEdit">编辑-->
<!--          </el-button>-->
<!--          <el-button-->
<!--            v-if="deptManager_btn_del"-->
<!--            type="primary"-->
<!--            icon="delete"-->
<!--            @click="handleDelete">删除-->
<!--          </el-button>-->
<!--        </el-button-group>-->
<!--      </div>-->

      <el-row>
        <el-col
          :span="8"
          style="margin-top:15px;">
          <div class="dev-type-main-left">
            <!--鼠标右键菜单栏 -->
            <div v-show="showRightMenu">
              <ul id="menu"
                  class="right-menu">
                <li class="menu-item" style="text-indent: 10px;"
                    @click="addDevHandle">
                  新建子组织
                </li>
                <li class="menu-item"  style="text-indent: 10px;"
                    @click="editDevHandle">
                  修改
                </li>
                <li class="menu-item"  style="text-indent: 10px;"
                    @click="delDevHandle">
                  删除
                </li>
              </ul>
            </div>
            <el-tree
              :data="treeData"
              :props="defaultProps"
              :filter-node-method="filterNode"
              class="filter-tree"
              node-key="id"
              highlight-current
              default-expand-all
              @node-contextmenu="rightClick"
              @node-click="getNodeData"/>
          </div>
        </el-col>
        <el-col
          :span="16"
          style="margin-top:15px;">
          <el-card class="box-card" style="height: 550px !important;">
            <el-form
              ref="form"
              :label-position="labelPosition"
              :rules="rules"
              :model="form"
              label-width="80px">
              <el-form-item
                label="父级节点"
                prop="parentId">
                <el-input
                  v-model="form.parentId"
                  disabled
                  placeholder="请输入父级节点"/>
              </el-form-item>
              <el-form-item
                v-if="formEdit"
                label="节点编号"
                prop="deptId">
                <el-input
                  v-model="form.deptId"
                  :disabled="formEdit"
                  placeholder="节点编号"/>
              </el-form-item>
              <el-form-item
                label="机构名称"
                prop="name">
                <el-autocomplete
                  :min="1"
                  v-model="form.name"
                  :disabled="formEdit"
                  :fetch-suggestions="remoteMethod"
                  placeholder="请输入内容"
                  @select="handleSelect"
                ></el-autocomplete>

              </el-form-item>
<!--              <el-form-item-->
<!--                label="排序"-->
<!--                prop="sort">-->
<!--                <el-input-->
<!--                  v-model="form.sort"-->
<!--                  :disabled="disabled"-->
<!--                  type="number"-->
<!--                  placeholder="请输入排序"/>-->
<!--              </el-form-item>-->
              <el-form-item v-if="formStatus == 'update'">
                <el-button
                  type="primary"
                  @click="update">更新
                </el-button>
                <el-button @click="onCancel">取消</el-button>
              </el-form-item>
              <el-form-item v-if="formStatus == 'create'">
                <el-button
                  type="primary"
                  @click="create">保存
                </el-button>
                <el-button @click="onCancel">取消</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>
    </basic-container>
  </div>
</template>

<script>
  import {addObj, delObj, fetchTree, getObj, putObj} from '@/api/admin/dept'
  import {drugEntList} from '@/api/wmdadrugent'
  import {getAgentList} from '@/api/wmdaagent'
  import { mapGetters, mapState } from 'vuex'

  export default {
    name: 'Dept',
    data() {
      return {
        form: {
          name: null,
          sort: 0,
          parentId: null,
          deptId: null,
          level1Id:null,
          level1Name:null,
          level2Id:null,
          level2Name:null,
          level:null
        },
        showRightMenu: false,
        list: null,
        total: null,
        formEdit: true,
        formAdd: true,
        formStatus: '',
        orgList:[],
        levelCheck:0,
        treeData:[],
        typeOptions: ['0', '1'],
        methodOptions: ['GET', 'POST', 'PUT', 'DELETE'],
        listQuery: {
          name: undefined
        },
        restaurants: [],
        state: '',
        timeout:  null,
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        rules: {
          parentId: [
            {required: true, message: '请输入父级节点', trigger: 'blur'}
          ],
          deptId: [
            {required: true, message: '请输入节点编号', trigger: 'blur'}
          ],
          // name: [
          //   {required: true, message: '请输入部门名称', trigger: 'blur'},
          //   {min: 1, max: 32, message: '长度在 1 到 32 个字符', trigger: 'blur'}
          // ],
          // sort: [
          //   {required: true, message: '请输入排序值', trigger: 'blur'}
          // ]
        },
        labelPosition: 'right',
        currentId: 0,
        deptManager_btn_add: false,
        deptManager_btn_edit: false,
        deptManager_btn_del: false
      }
    },
    created() {
      this.getList()
      this.deptManager_btn_add = this.permissions['sys_dept_add']
      this.deptManager_btn_edit = this.permissions['sys_dept_edit']
      this.deptManager_btn_del = this.permissions['sys_dept_del']
    },
    computed: {
      ...mapGetters([
        'elements',
        'permissions',
        'userInfo'
      ])
    },
    // ...mapGetters([
    //
    // ]),
    methods: {
      createStateFilter(queryString) {
        return (state) => {
          return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      handleSelect(item) {
        this.form.deptId=Date.parse(new Date())/1000;
        if(this.levelCheck==1&&this.formStatus=="create"||this.formStatus=="update"&&(this.levelCheck-1)==1)
        {
          this.form.level1Id=item.key;
          this.form.level1Name=item.value;
        }else  if(this.levelCheck==2&&this.formStatus=="create"||this.formStatus=="update"&&(this.levelCheck-1)==2)
        {
          this.form.level2Id=item.key;
          this.form.level2Name=item.value;
        }else  if(this.levelCheck==3&&this.formStatus=="create"||this.formStatus=="update"&&(this.levelCheck-1)==3)
        {
          this.form.level3Id=item.key;
          this.form.level3Name=item.value;
        }
      },
      getList() {
        fetchTree(this.listQuery).then(response => {
          this.treeData = response.data.data
        })
      },
      filterNode(value, data) {
        if (!value) return true
        return data.label.indexOf(value) !== -1
      },
      getNodeData(data) {
        if (!this.formEdit) {
          this.formStatus = 'update'
        }
        this.form.deptId=data.id ;
        this.form.name=data.name ;
        this.form.parentId=data.parentId ;
        this.form.sort=data.sort ;
        // getObj(data.id).then(response => {
        //   this.form = response.data.data
        // })
        this.currentId = data.id

      },
      handlerEdit() {
        if (this.form.deptId) {
          this.formEdit = false
          this.formStatus = 'update'
        }
      },
      handlerAdd() {
        this.resetForm()
        this.formEdit = false
        this.formStatus = 'create'
      },
      handleDelete() {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delObj(this.currentId).then(() => {
            this.getList()
            this.resetForm()
            this.onCancel()
            this.$notify.success('删除成功')
          })
        })
      },
      update() {
        this.$refs.form.validate((valid) => {
          if (!valid) return
          if(undefined==this.form.deptId||null==this.form.deptId||""==this.form.deptId)
          {
            this.$notify.error('请选择组织')
          }

          this.form.level=this.levelCheck;
          this.form.sort=0;
          putObj(this.form).then(() => {
            this.getList()
            this.onCancel()
            this.$notify.success('更新成功')
          })
        })
      },
      create() {
        this.$refs.form.validate((valid) => {
          this.form.sort=0;
          if (!valid) return
          this.form.level=this.levelCheck+1;
          addObj(this.form).then(() => {
            this.getList()
            this.onCancel()
            this.$notify.success('创建成功')
          })
        })
      },
      onCancel() {
        this.formEdit = true
        this.formStatus = ''
      },
      resetForm() {
        this.form = {
          parentId: this.currentId
        }
      },
      remoteMethod(queryString, cb){
        this.form.level1Id=null;
        this.form.level1Name=null;
        this.form.level2Id=null;
        this.form.level2Name=null;
        this.form.level3Id=null;
        this.form.level3Name=null;
        this.form.deptId=null;
        this.restaurants=[];
        if(this.levelCheck==1&&this.formStatus=="create"||this.formStatus=="update"&&(this.levelCheck-1)==1)
        {
          var obj={
            entname:queryString
          };
          drugEntList(obj).then(response => {
            var res = response.data.data
            if (undefined != res) {
              for (var i = 0; i < res.length; i++) {
                this.restaurants.push({
                  name: res[i].id,
                  value: res[i].entname,
                  label: res[i].entname,
                  key: res[i].id
                });
              }
            }
            var restaurants = this.restaurants;
            var results =restaurants;
            clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
              cb(results);
            }, 1000 );
          })
        }else  if(this.levelCheck==2&&this.formStatus=="create"||this.formStatus=="update"&&(this.levelCheck-1)==2)
        {
          var obj={
            gsmc:queryString
          };
          getAgentList(obj).then(response => {
            var res = response.data.data
            if (undefined != res) {
              for (var i = 0; i < res.length; i++) {
                this.restaurants.push({
                  name: res[i].id,
                  value: res[i].gsmc,
                  label: res[i].gsmc,
                  key: res[i].id
                });
              }
            }
            var restaurants = this.restaurants;
            var results = restaurants;

            clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
              cb(results);
            }, 1000 );
          })
        }else  if(this.levelCheck==3&&this.formStatus=="create"||this.formStatus=="update"&&(this.levelCheck-1)==3)
        {
          var obj={
            gsmc:queryString
          };
          getAgentList(obj).then(response => {
            var res = response.data.data
            if (undefined != res) {
              for (var i = 0; i < res.length; i++) {
                this.restaurants.push({
                  name: res[i].id,
                  value: res[i].gsmc,
                  label: res[i].gsmc,
                  key: res[i].id
                });
              }
            }
            var restaurants = this.restaurants;
            var results = restaurants;

            clearTimeout(this.timeout);
            this.timeout = setTimeout(() => {
              cb(results);
            }, 1000 );
          })
        }
      },
      rightClick(event, data, node, obj) {
        this.currentId = data.id
        this.form.deptId=data.id ;
        this.form.name=data.name ;
        this.form.parentId=data.parentId ;
        this.form.sort=data.sort ;
        this.levelCheck=node.level;
        this.showRightMenu = false // 先把模态框关死，目的是：第二次或者第n次右键鼠标的时候 它默认的是true
        this.showRightMenu = true

        if(!data.isLock)
        {
        //判断是几级菜单
          //let level=data.
          let menu = document.querySelector('#menu')
          menu.style.left = event.clientX -200 + 'px'
          menu.style.top = event.clientY - 140 + 'px'
          // 给整个document添加监听鼠标事件，点击任何位置执行closeRightMenu方法，及时将菜单关闭
          document.addEventListener('click', this.closeRightMenu)
          console.log('event', event, event.clientX, event.clientY)
          console.log('data', data)
          console.log(node)
        }else{
          this.showRightMenu = false
          document.removeEventListener('click', this.closeRightMenu)
        }

      },
      closeRightMenu() {
        this.showRightMenu = false
        // 及时关掉鼠标监听事件
        document.removeEventListener('click', this.closeRightMenu)
      },
      addDevHandle() {

        let userinfo=this.userInfo;
        let roles=userinfo.roles;
        var isAdmin=false;
        var isEnt=false;
        var isAg=false;
        for(var i =0;i<roles.length;i++)
        {
          if(1==roles[i]||2==roles[i])
          {
            isAdmin=true;
          }else  if(3==roles[i])
          {
            isEnt=true;
          }else  if(4==roles[i])
          {
            isAg=true;
          }
        }

        // if(isAdmin&&this.levelCheck>1)
        // {
        //   this.$notify.error('平台管理员只能创建药企架构')
        //   return false;
        // }
        //
        //
        // if(isEnt&&this.levelCheck>2)
        // {
        //   this.$notify.error('药企只能创建一级代理商架构')
        //   return false;
        // }


        if(this.levelCheck>3)
        {
          this.$notify.error('二级代理商不能够创建子组织')
          return false;
        }
        this.resetForm()
        this.formEdit = false
        this.formStatus = 'create'
      },
      editDevHandle() {
        if (this.form.deptId) {
          this.formEdit = false
          this.formStatus = 'update'
        }
      },
      // 删除操作
      delDevHandle() {

        let userinfo=this.userInfo;
        let roles=userinfo.roles;
        var isAdmin=false;
        var isEnt=false;
        var isAg=false;
        for(var i =0;i<roles.length;i++)
        {
          if(3==roles[i])
          {
            isAdmin=true;
          }else  if(4==roles[i])
          {
            isEnt=true;
          }
        }

        if(isAdmin)
        {
          if(this.levelCheck==2)
          {
            this.$notify.error('事业部管理员不能够删除自己药企组织')
            return false;
          }
        }


        if(isEnt)
        {
          if(this.levelCheck==3)
          {
            this.$notify.error('CSO管理员不能够删除自己组织')
            return false;
          }
        }

        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delObj(this.currentId).then(() => {
            this.getList()
            this.resetForm()
            this.onCancel()
            this.$notify.success('删除成功')
          })
        })
      }
    }
  }
</script>

<style lang="scss" scoped>


  ::v-deep .el-input__inner {
    width: 500px!important;
  }

  .dev-type-main-left {
    overflow: auto;
    padding: 10px;

    .right-menu {
      z-index: 1;
      position: absolute;
      height: 100px;
      width: 150px;
      position: absolute;
      border-radius: 5px;
      border: 1px solid #ccc;
      background-color: white;

      .menu-item {
        display: block;
        line-height: 20px;
        text-align: left;
        margin-top: 10px;
        font-size: 14px;
        color: #606266;
      }

      li:hover {
        background-color: #edf6ff;
        color: #606266;
      }

    }
  }

</style>
