<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="部门名称" prop="orgName">
        <el-input
          v-model="queryParams.orgName"
          placeholder="请输入部门名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="orgHeadUserName">
        <el-input
          v-model="queryParams.orgHeadUserName"
          placeholder="请输入部门负责人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="deptList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="orgName" label="部门名称" width="260"></el-table-column>
      <el-table-column prop="orgHeadUserName" label="部门负责人" width="200"></el-table-column>
      <el-table-column prop="attendanceUserName" label="考勤员" width="200"></el-table-column>
      <el-table-column prop="isProvince" label="省内、外" width="100">
        <template slot-scope="scope">
          <!-- <div v-if="scope.row.isProvince==1">省内</div>
          <div v-if="scope.row.isProvince==0">省外</div> -->
          <!-- <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.isProvince"/> -->
        </template>
      </el-table-column>
      <el-table-column prop="address" label="位置"></el-table-column>
      <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
          >新增</el-button>
          <el-button
            v-if="scope.row.parentId != 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <treeselect v-model="form.parentId" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级部门" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="部门名称" prop="orgName">
              <el-input v-model="form.orgName" placeholder="请输入部门名称" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
       
        <el-row>
          <el-col :span="24">
            <el-form-item label="部门负责人" prop="orgHeadUserId">
              <treeselect v-model="form.orgHeadUserId" :flat="true" :options="personOptions" :normalizer="normalizer2" placeholder="选择部门负责人" @select="handleSelect1"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="考勤员" prop="attendanceUserId">
              <treeselect v-model="form.attendanceUserId" :flat="true" :options="personOptions" :normalizer="normalizer2" placeholder="选择考勤员" @select="handleSelect2"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="省份" prop="province">
              <el-select v-model="form.province" placeholder="省份" clearable>
                <el-option
                  v-for="item in provinceList"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="省内外" prop="isProvince">
              <el-radio-group v-model="form.isProvince">
                <el-radio
                  v-for="item in isProvinceList"
                  :key="item.id"
                  :label="item.id"
                >{{item.name}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="是否项目部" prop="isDepartment">
              <el-radio-group v-model="form.isDepartment">
                <el-radio
                  v-for="item in isDepartmentList"
                  :key="item.id"
                  :label="item.id"
                >{{item.name}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="位置" prop="address">
              <el-input v-model="form.address" placeholder="请输入位置" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDept, getDept, delDept, addDept, updateDept,orgPersonSelect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Dept",
  dicts: ['sys_is_province'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      deptList: [],
      // 部门树选项
      deptOptions: [],
      personOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        orgName: undefined,
        orgHeadUserName: undefined
      },
      isProvinceList:[{id:'1',name:'省内'},{id:'2',name:'省外'}],
      isDepartmentList:[{id:'0',name:'否'},{id:'1',name:'是'}],
      provinceList:["北京","上海","天津",
                    "重庆",
                    "河北",
                    "山西",
                    "内蒙古",
                    "辽宁",
                    "吉林",
                    "黑龙江",
                    "江苏",
                    "浙江",
                    "安徽",
                    "福建",
                    "江西",
                    "山东",
                    "河南",
                    "湖北",
                    "湖南",
                    "广东",
                    "广西",
                    "海南",
                    "四川",
                    "贵州",
                    "云南",
                    "西藏",
                    "陕西",
                    "甘肃",
                    "宁夏",
                    "青海",
                    "新疆",
                    "香港",
                    "澳门",
                    "台湾"],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级部门不能为空", trigger: "blur" }
        ],
        orgName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" }
        ],
        orgHeadUserId: [
          { required: true, message: "部门负责人不能为空", trigger: "blur" }
        ],
        attendanceUserId: [
          { required: true, message: "考勤员不能为空", trigger: "blur" }
        ],
        province: [
          { required: true, message: "省份不能为空", trigger: "blur" }
        ],
        isProvince: [
          { required: true, message: "省内外不能为空", trigger: "blur" }
        ],
        isDepartment: [
          { required: true, message: "是否项目部不能为空", trigger: "blur" }
        ],
        address: [
          { required: true, message: "位置不能为空", trigger: "blur" }
        ],
         
      }
    };
  },
  mounted() {
    this.getList();
    this.orgPersonSelect();
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      listDept(this.queryParams).then(response => {
        this.deptList = this.handleTree(response.data, "id");
        this.loading = false;
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.orgName,
        children: node.children
      };
    },
    normalizer2(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        parentId: undefined,
        orgName: undefined,
        address: undefined,
        attendanceUserId: undefined,
        attendanceUserName: undefined,
        orgHeadUserId: undefined,
        orgHeadUserName: undefined,
        province: undefined,
        isProvince: "1",
        isDepartment: "0",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.id;
      }
      this.open = true;
      this.title = "添加部门";
      listDept().then(response => {
        this.deptOptions = this.handleTree(response.data, "id");
      });
    },
    /** 人员选择下拉 */
    orgPersonSelect() {
      orgPersonSelect().then(response => {
        this.personOptions=this.changeData(response.data);
        // this.personOptions = this.handleTree(response.data, "id");
        console.log(this.personOptions)
      });
    },
    //数据操作
    changeData(data)  { // 存在子集就不让禁止，父级让禁止
      data.map(item => {
        if (!item.disabled) {
          item.isDisabled = false
        } else if (item.disabled){
          item.isDisabled = true
        }
        item.children && item.children.length > 0 && this.changeData(item.children);
      })
      return data;
    },
    handleSelect1(value, instanceId) { 
      console.log('Selected:', value);
      // 在这里处理选择事件
      this.form.orgHeadUserName=value.name;
    },
    handleSelect2(value, instanceId) { 
      console.log('Selected:', value);
      // 在这里处理选择事件
      this.form.attendanceUserName=value.name;
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getDept(row.id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改部门";
        listDept().then(response => {
          this.deptOptions = this.handleTree(response.data, "id");
        });
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateDept(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDept(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.orgName + '"的数据项？').then(function() {
        return delDept(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
<style scoped>
.vue-treeselect__option--highlighted {
  background-color: initial; /* 或者你想要的任何颜色 */
  color: initial; /* 或者你想要的任何颜色 */
}
</style>