<template>
  <div>
    <el-card>
      <el-form :model="query" v-if="showSearch" label-width="auto">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="所属科室">
              <deptSelect :value.sync="query.deptCode"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="top-right-btn">
        <el-button-group>
          <el-button icon="el-icon-view" type="primary" @click="showSearch = !showSearch">显示/隐藏搜索栏</el-button>
          <el-button
            type="primary"
            icon="el-icon-refresh"
            @click="onReset"
          >重置
          </el-button>
          <el-button type="primary" icon="el-icon-search" @click="search"
          >查询
          </el-button>
          <el-button type="primary" icon="el-icon-plus" @click="add"
          >添加
          </el-button>
        </el-button-group>
      </div>
    </el-card>
    <el-card>
      <el-row>
        <el-col :span="24">
          <el-table
            :data="dataList"
            border
            width="100%"
            :header-cell-style="{ 'text-align': 'center' }"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            :row-key="(record) => record.categoryId"
            :row-style="{height: '10'}"
          >
            <el-table-column
              label="分类ID"
              prop="categoryId"
              align="center"
            ></el-table-column>
            <el-table-column label="父级分类ID" align="center">
              <template slot-scope="scope">
                {{ scope.row.parentCategoryId == null ? '-' : scope.row.parentCategoryId }}
              </template>
            </el-table-column>
            <el-table-column
              label="分类名称"
              prop="categoryName"
              align="center"
            ></el-table-column>

            <el-table-column
              label="分类级别"
              prop="level"
              align="center"
            ></el-table-column>

            <el-table-column
              label="分类描述"
              prop="description"
              align="center"
            ></el-table-column>

            <el-table-column
              label="操作"
              align="center"
            >
              <template slot-scope="scope">
              <el-button-group style="margin-bottom: 8px; margin-top: 8px;">
                <el-button type="danger"  @click.native="del(scope.row)" :loading="loading">删除</el-button>
              </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog
      title="添加科室医保分类绑定"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="selectDialog"
      width="65%"
      append-to-body
      v-if="selectDialog"
    >
      <el-form :model="addData" label-width="auto">

        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="所属科室">
              <deptSelect :value.sync="addData.deptCode" />
            </el-form-item>
          </el-col>
          <el-col :span="4" :offset="14" >
            <el-button-group >
              <el-button type="primary"  @click.native="save()" :loading="saveLoading">保存</el-button>
            </el-button-group>
          </el-col>
        </el-row>

      <el-form-item label="医保分类绑定">
        <el-checkbox v-model="categoryExpand" @change="handleCheckedTreeExpand($event, 'deptCategory')">展开/折叠</el-checkbox>
        <el-checkbox v-model="categoryNodeAll" @change="handleCheckedTreeNodeAll($event, 'deptCategory')">全选/全不选</el-checkbox>
        <el-tree
          props="categoryOptions"
          class="tree-border"
          :data="categoryOptions"
          show-checkbox
          ref="deptCategory"
          node-key="id"
          empty-text="加载中，请稍候"
          :props="defaultProps"
        ></el-tree>
      </el-form-item>

      </el-form>
    </el-dialog>

  </div>
</template>


<script>
import { deptCategoryTreeselect , deptCategoryList , updateBindCategory , deleteBindCategory } from '@/api/basic/consume/materialCategory'

export default {
  name: 'materialCategory',
  data() {
    return {
      data: [],
      showSearch:true,
      query:{
        deptCode: this.$store.getters.locDeptCode,
      },
      addData:{
        deptCode: null,
        deptCategory: [],
      },
      selectDialog:false,
      categoryExpand:false,
      categoryNodeAll:false,
      categoryOptions:[],
      defaultProps: {
        children: "children",
        label: "label"
      },
      saveLoading: false,
    }
  },
  methods: {
    save(){
      this.addData.deptCategory = this.getDeptAllCheckedKeys()
      this.saveLoading = true
      updateBindCategory(this.addData).then((response) => {
        if (response.code == 20000) {
          this.saveLoading = false
          this.selectDialog = !this.selectDialog
          this.getData(this.query.deptCode)
          this.$message.success("保存成功");
        } else {
          this.$message.error(response.message);
        }
      }).catch(() => {
        this.saveLoading = false
          this.$message.error("保存失败");
        });
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.deptCategory.getCheckedKeys();
      // 半选中的部门节点
      // let halfCheckedKeys = this.$refs.deptCategory.getHalfCheckedKeys();
      // checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    handleUpdate(deptCode) {
      const deptCategory = this.getDeptCategoryTreeselect(deptCode)
      this.$nextTick(() => {
        deptCategory.then(res => {
          let checkedKeys = res.data.checkedKeys
          checkedKeys.forEach((v) => {
            this.$nextTick(() => {
              this.$refs.deptCategory.setChecked(v, true, false)
            })
          })
        })
      })
    },
    /** 根据deptCode查询菜单树结构 */
    getDeptCategoryTreeselect(deptCode) {
      return deptCategoryTreeselect(deptCode).then(response => {
        this.categoryOptions = response.data.categorys;
        return response;
      });
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'deptCategory') {
        let treeList = this.categoryOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.deptCategory.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'deptCategory') {
        this.$refs.deptCategory.setCheckedNodes(value ? this.categoryOptions : []);
      }
    },
    //获取结构树
    getTrees(list, parentCategoryId = 0) {
      let parentObj = {}
      list.forEach((o) => {
        parentObj[o.categoryId] = o
      })
      if (!parentCategoryId) {
        return list
          .filter((o) => !parentObj[o.parentCategoryId])
          .map((o) => ((o.children = this.getTrees(list, o.categoryId)), o))
      } else {
        return list
          .filter((o) => o.parentCategoryId == parentCategoryId)
          .map((o) => ((o.children = this.getTrees(list, o.categoryId)), o))
      }
    },
    //初始化数据
    async  getData(deptCode) {
       deptCategoryList(deptCode).then(response => {
        var data = response.data;
        if ( data == null || data == [] ){
          this.dataList = []
          return;
        }else {
          this.dataList = this.getTrees(data)
          this.$forceUpdate();
        }
        });
    },
    search(){
      this.getData(this.query.deptCode)
    },
    add(){
      this.addData.deptCode = this.query.deptCode
      this.handleUpdate(this.addData.deptCode)
      this.selectDialog = !this.selectDialog
    },
    del(row){
      let ids = []
      let children = row.children
      ids.push(row.categoryId)
      if (children.length > 0 ){
        for (let i = 0; i < children.length; i++) {
          ids.push(children[i].categoryId)
        }
      }
      //如果一级节点 无子节点也删除
      this.dataList.forEach( x => {
        let  targetArray = []
        if(x.level == 1) {
          for (let i = 0; i < x.children.length; i++) {
            targetArray.push(x.children[i].categoryId)
          }
          if (this.arrayContainsAll(ids, targetArray))
            ids.push(x.categoryId)
        }
      })

      let del = {
        deptCode: this.query.deptCode,
        deptCategory: ids
      }
      //调用删除
      deleteBindCategory(del).then((response) => {
        if (response.code == 20000) {
          this.getData(this.query.deptCode)
          this.$message.success("删除成功");
        } else {
          this.$message.error(response.message);
        }
      }).catch(() => {
        this.$message.error("删除失败");
      });
    },
    onReset(){
      this.query.deptCode = this.$store.getters.locDeptCode
    },
    arrayContainsAll(sourceArray, targetArray) {
      return targetArray.every(item => sourceArray.includes(item))
    }

  },
  watch:{
    'query.deptCode'(newVal, oldVal) {               //监听数据被修改时触发，默认初始化时，不会触发
      this.getData(newVal)
    },
    'addData.deptCode'(newVal, oldVal) {               //监听数据被修改时触发，默认初始化时，不会触发
      this.handleUpdate(newVal)
    }

  },
  mounted() {
    this.getData(this.$store.getters.locDeptCode)
  },
  created() {

  }
}
</script>

<style scoped>

</style>
