<template>
  <div class="content-box">
    <div class="left">
      <!-- <el-icon :size="23" class="camera"><VideoCameraFilled /></el-icon> -->
      <span class="cameratxt">员工管理</span>
    </div>
    <div>
      <div class="middle">
        <div class="filter">
          <div class="condition">
            <span>关键字 : </span>
            <el-input :clearable="true" @clear="searchBtn" v-model="searchInput.keyWord" class="w-50 m-2"
              placeholder="请输入姓名" style="width: 150px" />
          </div>
          <div class="condition">
            <span>维修班 : </span>
            <el-select :clearable="true" @clear="searchBtn" v-model="searchInput.teamId" class="m-2" placeholder="请选择维修班">
              <el-option label="校方人员" :value="0" />
              <el-option label="第三方人员" :value="1" />
            </el-select>
          </div>
          <div class="condition">
            <span>校区 : </span>
            <el-select :clearable="true" @clear="searchBtn" v-model="searchInput.schoolId" class="m-2"
              placeholder="请选择校区">
              <el-option label="黄家湖校区" :value="1" />
              <el-option label="墨轩湖校区" :value="2" />
            </el-select>
          </div>

          <el-button style="margin-left: 20px" color="rgba(111, 182, 184, 1)" type="primary" class="search"
            @click="searchBtn"><el-icon>
              <Search />
            </el-icon> <span>查询</span></el-button>
        </div>
        <!-- 按钮列表 -->
        <div class="gongneng">
          <el-button type="primary" color="rgba(111, 182, 184, 1)" @click="addlist"><img src="@/assets/add.png"
              style="width: 14px; height: 14px; margin-right: 4px" alt="" /><span>添加员工</span></el-button>
        </div>
      </div>
      <div class="footer">
        <el-table :row-class-name="tableRowClassName" :data="tableData.list" @selection-change="handleSelectionChange"
          style="width: 100%" :header-cell-style="{
            background: 'rgba(240, 243, 247, 1)',
            height: '50px',
            border: 0,
          }">
          <!-- <el-table-column align="center" type="selection" width="80" /> -->
          <el-table-column width="80" align="center " type="index" label="序号" />
          <el-table-column align="center" prop="userName" label="姓名" />
          <el-table-column align="center" width="150" prop="userPhone" label="手机号码" />
          <el-table-column align="center" prop="teamName" label="维修班" />
          <el-table-column align="center" prop="schoolName" label="校区" />
          <el-table-column align="center" prop="userZzname" label="身份" />

          <el-table-column align="center" width="200" prop="buildName" label="关联楼栋" show-overflow-tooltip>
            <!-- <template #default="{ row }">
              <span>{{  }}</span>
            </template> -->
          </el-table-column>
          <el-table-column align="center" width="100" prop="workTypeName" label="工种" />
          <el-table-column align="center" prop="articleName" label="关联报修类型" width="200" show-overflow-tooltip />
          <!-- <el-table-column align="center" prop="acceptanceTime" label="接单考核时间" /> -->
          <!-- <el-table-column align="center" prop="maintenanceTime" label="维修考核时间" /> -->
          <el-table-column align="center" fixed="right" label="操作" width="150">
            <template #default="scope">
              <div class="edit">
                <div class="look" @click="edit(scope.row)">编辑</div>
                <el-popconfirm width="220" confirm-button-text="确认" cancel-button-text="取消" :icon="InfoFilled"
                  icon-color="#f89626" title="是否删除此员工?" @confirm="del(scope.row)" @cancel="cancelEvent">
                  <template #reference>
                    <div class="look">删除</div>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 添加耗材弹窗 -->
        <el-dialog class="addStaff" v-model="addDialogVisible" :close-on-click-modal="false"
          :close-on-press-escape="false" :title="dialongTitle" align-center width="700" :before-close="cancelAdd">
          <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
            size="default" label-position="left" status-icon>
            <el-form-item label="身份 :" prop="userzzId">
              <el-select v-model="ruleForm.userzzId" @change="changeUserZzid" class="m-2" placeholder="请选择身份">
                <el-option v-for="item in userzzIdsList" :label="item.name" :value="item.id" v-show="item.id !== 0" />
              </el-select>
            </el-form-item>
            <el-form-item label="姓名 :" prop="userName">
              <el-input v-model="ruleForm.userName" placeholder="请输入姓名" clearable />
            </el-form-item>
            <el-form-item label="维修班 :" prop="teamId">
              <el-select v-model="ruleForm.teamId" class="m-2" placeholder="请选择维修班">
                <el-option label="校方人员" :value="0" />
                <el-option label="第三方人员" :value="1" />
              </el-select>
            </el-form-item>
            <el-form-item label="微校卡号 :" prop="cardNumber" v-if="dialongTitle == '添加员工' && ruleForm.userzzId != 4">
              <el-input v-model="ruleForm.cardNumber" placeholder="请输入微校卡号" clearable />
            </el-form-item>
            <el-form-item label="微校卡号 :" prop="cardNumber" v-if="dialongTitle == '编辑员工' && ruleForm.userzzId != 4">
              <el-input v-model="ruleForm.cardNumber" disabled placeholder="请输入微校卡号" clearable />
            </el-form-item>

            <el-form-item label="手机号码 :" prop="userPhone" v-if="ruleForm.userzzId != 4">
              <el-input v-model="ruleForm.userPhone" placeholder="请输入手机号码" clearable />
            </el-form-item>
            <el-form-item label="校区 :" prop="schoolId">
              <el-select v-model="ruleForm.schoolId" class="m-2" placeholder="请选择校区" @change="changeSchool">
                <el-option label="黄家湖校区" :value="1" />
                <el-option label="墨轩湖校区" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="工种 :">
              <el-select v-model="ruleForm.workType" clearable class="m-2" placeholder="请选择工种">
                <el-option v-for="item in workTypeList" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="关联报修类型 :" prop="articleBuilds" class="checkbox" v-if="ruleForm.userzzId != 4">
              <div class="type">
                <div class="articleType">
                  <div class="articleTitle">关联种类</div>
                  <!-- <el-checkbox v-model="articleAll" :indeterminate="articleIndeterminate"
                    @change="articleAllChange">全选</el-checkbox> -->
                  <el-tree :data="articleIdsList" @node-click="articleNodeClick"
                    :props="{ label: 'name', children: 'children', value: 'id' }" node-key="id" show-checkbox
                    ref="articleIdsRef" @check-change="handleArticleIds">
                    <template #default="{ node, data }">
                      <div class="custom-tree-node">
                        <span>{{ data.name }}</span>
                        <img v-if="data.id == clickArticleSel.id" src="../../assets/fixed.png" alt="">
                        <img v-else src="" alt="">
                      </div>
                    </template>
                  </el-tree>
                </div>
                <div class="buildType">
                  <div class="allAriticle">
                    <div class="articleTitle">关联楼栋</div>
                    <!-- <el-checkbox v-model="buildAll" :indeterminate="buildIndeterminate"
                      @change="buildAllChange">全选</el-checkbox> -->
                  </div>
                  <el-tree :data="treeValue.list" :props="{ label: 'name', children: 'children', value: 'id' }"
                    node-key="id" show-checkbox ref="buildIdsRef" @check-change="handleCheckChange" />
                </div>
              </div>
              <!-- <div class="type" v-if="ruleForm.schoolId == 2">
                <div class="articleType">
                  <div class="articleTitle">关联种类</div>
                 

                  <el-tree :data="articleIdsList" @node-click="articleNodeClick"
                    :props="{ label: 'name', children: 'children', value: 'id' }" node-key="id" show-checkbox
                    ref="articleIdsRef" @check-change="handleArticleIds">
                    <template #default="{ node, data }">
                      <span class="custom-tree-node">
                        <span>{{ data.name }}</span>
                        <img v-if="data.id == clickArticleSel.id" src="../../assets/fixed.png" alt="">
                        <img v-else src="" alt="">
                      </span>
                    </template>
                  </el-tree>
                </div>
                <div class="buildType">
                  <div class="allAriticle">
                    <div class="articleTitle">关联楼栋</div>
                  
                  </div>

                  <el-tree :data="treeValue.list" :props="{ label: 'name', children: 'children', value: 'id' }"
                    node-key="id" show-checkbox ref="buildIdsRef" @check-change="handleCheckChange" />
                </div>
              </div> -->
            </el-form-item>
            <!-- <el-form-item label="关联楼栋 :" prop="buildIds" v-if="ruleForm.userzzId != 4">
              <el-tree :data="treeValue.list" :props="{ label: 'name', children: 'children', value: 'id' }" node-key="id"
                show-checkbox ref="buildIdsRef" @check-change="handleCheckChange" />
            </el-form-item> -->
            <el-form-item label="接单考核时间 :" v-if="ruleForm.userzzId != 4">
              <div class="kaohe">
                <el-input v-model="ruleForm.acceptanceTime" :clearable="false" placeholder="考核时间" style="width: 150px">
                  <template #suffix>
                    <img src="@/assets/timer.png" alt="" style="width: 15px; height: 15px" />
                  </template>
                </el-input>
                <span style="margin-left: 5px">分钟</span>
              </div>
            </el-form-item>
            <el-form-item style="
                padding-bottom: 40px;
                border-bottom: 1px solid rgba(230, 230, 230, 1);
              " label="维修考核时间 :" v-if="ruleForm.userzzId != 4">
              <div class="kaohe">
                <el-input v-model="ruleForm.maintenanceTime" :clearable="false" placeholder="考核时间" style="width: 150px">
                  <template #suffix>
                    <img src="@/assets/timer.png" alt="" style="width: 15px; height: 15px" />
                  </template>
                </el-input>
                <span style="margin-left: 5px">分钟</span>
              </div>
            </el-form-item>

            <el-form-item class="options">
              <el-button color="rgba(111, 182, 184, 1)" class="queding" type="primary" @click="submitAdd(ruleFormRef)">
                确定
              </el-button>
              <el-button @click="cancelAdd(ruleFormRef)">取消</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>

      <!-- 分页组件 -->
      <div class="pageSize">
        <span></span>
        <el-pagination background :current-page="currentPage" :page-size="pageSize"
          layout="total, prev, pager, next, jumper, slot" :total="total" @update:current-page="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, onBeforeMount, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Calendar } from "@element-plus/icons-vue";
import vidiconsApi from "@/api/vidicons.js";
import { dayjs } from "element-plus";
import lodash from "lodash";
import axios from "axios";
import { useStore } from "vuex";
const store = useStore();
const api = ref("");
const router = useRouter();
// 表格数据
const tableData = reactive({
  list: [],
});

// 添加员工弹窗数据 (------------------------------------)
const dialongTitle = ref("添加员工"); // 弹窗标题

// 种类选择框数据
const articleAll = ref(false); // 判断物品种类是否全选
const articleIndeterminate = ref(false); // 不确定状态，表示只选择一部分
const articleIdsList = ref(); //  关联种类 类型数据
const articleIdsListM = ref(); //  关联种类 类型数据
const articleIdsListH = ref(); //  关联种类 类型数据


// 楼栋选择框数据
const buildAll = ref(false); // 判断楼栋 是否全选
const buildIndeterminate = ref(false); // 不确定状态，表示只选择一部分
const treeValue = reactive({
  list: [],
  listM: [],
  listH: [],
}); // 关联楼栋 树形结构数据

const userzzIdsList = ref(); //  身份下拉数据
const workTypeList = ref(); //  工种下拉数据
const props = reactive();


const searchInput = reactive({
  keyWord: "",
  teamId: "",
  schoolId: "",
}); // 搜索按钮数据

const currentPage = ref(1); // 当前页
const pageSize = ref(10);
const total = ref(); // 当前总数
const selectData = reactive({ list: [] }); // 多选框选择的数据

const addDialogVisible = ref(false); // 控制添加员工弹窗

// 添加员工表单数据
const formSize = ref("default");
const ruleFormRef = ref();
const articleIdsRef = ref(); // 关联报修类型ref
const buildIdsRef = ref(); // 关联楼栋ref
const ruleForm = reactive({
  userName: "",
  cardNumber: "",
  userzzId: "",
  userPhone: "",
  schoolId: "",
  workType: "",
  articleBuilds: [],
  // articleIds: [],
  // buildIds: [],
  teamId: "",
  acceptanceTime: "",
  maintenanceTime: "",
  id: "",
});
const articleBuilds = reactive({ list: [] }) // 选中的种类和楼栋组合数据
const clickArticleSel = reactive({
  id: "", name: ""
}); // 点击的那个种类

// 关联报修类型验证
const articleBuildRule = (rule, value, callback) => {
  console.log(rule, value);
  let sum = 0
  articleBuilds.list.forEach(item => {
    if (item.article.flag) {
      sum = item.build.length + sum
      console.log(sum);
    }
  }, 0)
  // console.log(sum);
  if (sum) {
    callback();
  } else {
    callback(new Error("关联报修类型不能为空"));
  }
};
// 表单验证
const rules = reactive({
  // serial: [{ required: true, message: "序列号不能为空", trigger: "blur" }],
  userName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  cardNumber: [
    { required: true, message: "微校卡号不能为空", trigger: "blur" },
  ],
  userzzId: [{ required: true, message: "身份不能为空", trigger: "change" }],
  userPhone: [{ required: true, message: "手机号码不能为空", trigger: "blur" }],
  schoolId: [{ required: true, message: "校区不能为空", trigger: "blur" }],
  workType: [{ required: true, message: "工种不能为空", trigger: "change" }],
  teamId: [{ required: true, message: "维修班不能为空", trigger: "change" }],
  articleBuilds: [
    // { required: true, message: "关联报修类型不能为空", trigger: "blur" },
    { required: true, validator: articleBuildRule, trigger: "blur" },
  ],
  articleIds: [
    { required: true, message: "关联报修类型不能为空", trigger: "blur" },
  ],
  buildIds: [{ required: true, message: "关联楼栋不能为空", trigger: "blur" }],
  acceptanceTime: [
    { required: true, message: "接单考核时间不能为空", trigger: "blur" },
  ],
  maintenanceTime: [
    { required: true, message: "维修考核时间不能为空", trigger: "blur" },
  ],
});

// 查看员工列表
const getList = async () => {
  let data = {
    currentPage: currentPage.value,
    pageCount: pageSize.value,
    keyWord: searchInput.keyWord,
    teamId: searchInput.teamId, // 维修班ID
    schoolId: searchInput.schoolId, // 校区ID
  };
  let res = await axios({
    method: "get",
    url: api.value + "/repairUser/queryPageRepairUser",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: data,
  });
  console.log(res, "用户列表");
  if (res.data.code == 200) {
    res.data.data.list.forEach((item) => {
      // 楼栋关联字段
      if (item.buildNames) {
        item.buildName = item.buildNames.join(",");
      } else {
        item.buildName = "暂无关联";
      }
      // 报修关联字段
      if (item.articleNames) {
        item.articleName = item.articleNames.join(",");
      } else {
        item.articleName = "暂无关联";
      }
    });
    tableData.list = res.data.data.list;
    // currentPage.value = res.data.currentPage;
    total.value = res.data.data.totalCount;
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
    if (res.data.code == 570) {
      sessionStorage.removeItem("token")
      router.push({
        path: `/login`,
      });
    }
  }
};

// 搜索功能
const searchBtn = lodash.debounce(async () => {
  getList();
}, 300);

// 关联种类和关联楼栋数据
// const treeValueList = async (val) => {
//   //  报修（故障类型）类型关联 (接口-------)
//   let data = {
//     schoolId: val,
//   };
//   let resss = await axios({
//     method: "get",
//     url: api.value + "/repairArticleType/queryRepairArticleType",
//     headers: {
//       token: sessionStorage.getItem("token"),
//       user_head: sessionStorage.getItem("userhead"),
//     },
//     params: data,
//   });
//   console.log(resss, "报修（故障类型）类型关联数据");
//   articleIdsList.value = resss.data.data;

//   // 关联楼栋数据 （接口---------）
//   let datas = { schoolId: val };
//   let res = await axios({
//     method: "get",
//     url: api.value + "/repairArea/queryRepairAreaSecond",
//     headers: {
//       token: sessionStorage.getItem("token"),
//       user_head: sessionStorage.getItem("userhead"),
//     },
//     params: datas,
//   });
//   console.log(res, "关联楼栋数据");
//   treeValue.list = res.data.data;

//   // 黄家湖校区
//   // if (val == 1) {
//   //   articleIdsListH.value = resss.data.data;
//   //   treeValue.listH = res.data.data;
//   // } // 墨轩湖
//   // else {
//   //   articleIdsListM.value = resss.data.data;
//   //   treeValue.listM = res.data.data;
//   // }
// }

// 切换身份时将种类和楼栋全部置空
const changeUserZzid = (val) => {
  clickArticleSel.id = ""
  clickArticleSel.name = ""
  if (articleBuilds.list) {
    articleBuilds.list.forEach(item => {
      item.article.flag = false;
      item.build = []
    })
  }
  nextTick(() => {
    articleIdsRef.value.setCheckedKeys([]);
    buildIdsRef.value.setCheckedKeys([]);
  });
}

// 改变校区  关联楼栋和关联报修类型也改变(---------------)
const changeSchool = async (val) => {
  // ruleForm.articleIds = [];
  // ruleForm.buildIds = [];
  clickArticleSel.id = "";
  clickArticleSel.name = "";
  console.log(clickArticleSel);

  nextTick(() => {
    // if (articleIdsRef.value && buildIdsRef.value) {
    articleIdsRef.value.setCheckedKeys([]);
    buildIdsRef.value.setCheckedKeys([]);
    // }
  });
  return new Promise(async (resolve, reject) => {
    /* 你的逻辑代码 */
    //  报修（故障类型）类型关联 (接口-------)
    let data = {
      schoolId: val,
    };
    let resss = await axios({
      method: "get",
      url: api.value + "/repairArticleType/queryRepairArticleType",
      headers: {
        token: sessionStorage.getItem("token"),
        user_head: sessionStorage.getItem("userhead"),
      },
      params: data,
    });
    console.log(resss, "报修（故障类型）类型关联数据");
    articleIdsList.value = resss.data.data;

    // 关联楼栋数据 （接口---------）
    let datas = { schoolId: val };
    let res = await axios({
      method: "get",
      url: api.value + "/repairArea/queryRepairAreaSecond",
      headers: {
        token: sessionStorage.getItem("token"),
        user_head: sessionStorage.getItem("userhead"),
      },
      params: datas,
    });
    console.log(res, "关联楼栋数据");
    treeValue.list = res.data.data;

    articleBuilds.list = []
    articleIdsList.value.forEach(item => {
      articleBuilds.list.push({
        article: { id: item.id, name: item.name, flag: false },
        build: [],
        id: ""
      })
    })
    console.log(articleBuilds.list, "整理的树形数据");
    resolve('success')
    console.log("1111111111111111111111111111111");

  });

};

//新增员工 （--------------------------------------）
const addlist = async () => {
  dialongTitle.value = "添加员工";
  addDialogVisible.value = true;
  ruleForm.userName = "";
  ruleForm.cardNumber = "";
  ruleForm.userzzId = "";
  ruleForm.userPhone = "";
  ruleForm.workType = "";
  // ruleForm.articleIds = [];
  // ruleForm.buildIds = [];
  ruleForm.teamId = "";
  ruleForm.acceptanceTime = "";
  ruleForm.maintenanceTime = "";
  ruleForm.schoolId = 1;
  ruleForm.id = "";
  clickArticleSel.id = ""
  clickArticleSel.name = ""

  changeSchool(1)

  nextTick(() => {
    articleIdsRef.value.setCheckedKeys([]);
    buildIdsRef.value.setCheckedKeys([]);
  });
};

// 种类是否全选操作
// const articleAllChange = (val) => {
//   console.log(val);
//   console.log(articleIdsList.value);
//   let articleIds = []
//   // 黄家湖
//   if (val) {
//     articleIdsList.value.forEach((item) => {
//       articleIds.push(item.id);
//     });
//     articleIdsRef.value.setCheckedKeys(articleIds)
//   } else {
//     console.log("取消全选");
//     articleIdsRef.value.setCheckedKeys([])
//     // articleIndeterminate.value = false;
//   }
// };
// //单独勾选种类
// const handleCheckedCitiesChange = (value) => {
//   console.log(value);
//   const checkedCount = value.length;
//   checkAll.value = checkedCount === articleIdsList.value.length;
//   isIndeterminate.value =
//     checkedCount > 0 && checkedCount < articleIdsList.value.length;
// };

// 单独勾选种类 当复选框被点击的时候触发
const handleArticleIds = (data, checked, indeterminate) => {
  console.log(data, checked, indeterminate, "单独勾选种类");
  // let keys = articleIdsRef.value.getCheckedNodes();

  // 判断当前勾选的是哪个种类
  // if (checked) {
  //   clickArticleSel.name = data.name
  //   clickArticleSel.id = data.id
  // }
  clickArticleSel.name = data.name
  clickArticleSel.id = data.id

  let keys = articleIdsRef.value.getCheckedKeys();
  console.log(keys);
  // 黄家湖
  // if (keys.length == articleIdsList.value.length) {
  //   articleIndeterminate.value = false;
  //   articleAll.value = true
  // } else if (keys.length) {
  //   articleAll.value = false
  //   articleIndeterminate.value = true;
  // } else {
  //   articleAll.value = false
  //   articleIndeterminate.value = false;
  // }

  // 判断是否勾选时赋值
  articleBuilds.list.forEach(item => {
    // console.log(item);

    if (item.article.id == data.id) {
      item.article.flag = checked
      // if (item.article.flag) {
      // buildIdsRef.value.setCheckedKeys(item.build);
      // }
      buildIdsRef.value.setCheckedKeys(item.build);
    }
  })

  console.log(articleBuilds.list);
  // ruleForm.articleIds = keys;
};

// 关联种类 被点击时触发
const articleNodeClick = (data, node, component) => {
  //  * @description: node - click 节点被点击时的回调
  //  * @param {*} data 该节点所对应的对象
  //  * @param {*} node 节点对应的 Node
  //  * @param {*} component 节点组件本身
  console.log('子组件触发 node-click 事件', data, node, component);
  // 判断是否击
  clickArticleSel.name = data.name
  clickArticleSel.id = data.id
  articleBuilds.list.forEach(item => {
    // console.log(item);

    if (item.article.id == data.id) {
      // item.article.flag = checked
      // if (item.article.flag) {
      // buildIdsRef.value.setCheckedKeys(item.build);
      // }
      buildIdsRef.value.setCheckedKeys(item.build);
    }
  })
}

//  关联楼栋 当复选框被勾选的时候触发
const handleCheckChange = (data, checked, indeterminate) => {
  // console.log(data, checked);
  let keys = buildIdsRef.value.getCheckedNodes();
  console.log(keys);

  // let buildAllLength = 0;
  // buildAllLength = treeValue.list.reduce((pre, cur) => {
  //   return cur.children.length + pre
  // }, treeValue.list.length)

  // if (keys.length == buildAllLength) {
  //   buildIndeterminate.value = false;
  //   buildAll.value = true
  // } else if (keys.length) {
  //   buildAll.value = false
  //   buildIndeterminate.value = true;
  // } else {
  //   buildAll.value = false
  //   buildIndeterminate.value = false;
  // }

  let arr = [];
  keys.forEach((item) => {
    if (item.parentId != 1) {
      arr.push(item.id);
    }
  });
  articleBuilds.list.forEach(item => {
    if (item.article.id == clickArticleSel.id) {
      item.build = arr
    }
  })
  console.log(articleBuilds.list);
};

// 楼栋被全选时
const buildAllChange = (val) => {
  console.log(val);
  console.log(treeValue.list);

  nextTick(() => {
    if (val) {
      let buildIds = []
      treeValue.list.forEach(item => {
        item.children.forEach(i => {
          buildIds.push(i.id)
        })
      })
      buildIdsRef.value.setCheckedKeys(buildIds);
    } else {
      buildIdsRef.value.setCheckedKeys([]);
    }
  })
}

//编辑按钮  （-------------------------------------------）
const edit = (row) => {
  dialongTitle.value = "编辑员工";
  addDialogVisible.value = true;

  clickArticleSel.id = "";
  clickArticleSel.name = "";

  changeSchool(row.schoolId).then(res => {
    if (row.userZzid == 4) {
      ruleForm.userName = row.userName;
      ruleForm.userzzId = row.userZzid;
      ruleForm.workType = row.workType;
      ruleForm.teamId = row.teamId;
      ruleForm.schoolId = row.schoolId;
      ruleForm.id = row.id;
    } else {
      ruleForm.userName = row.userName;
      ruleForm.cardNumber = row.cardNumber;
      ruleForm.userzzId = row.userZzid;
      ruleForm.userPhone = row.userPhone;
      ruleForm.schoolId = row.schoolId;
      ruleForm.workType = row.workType;
      ruleForm.teamId = row.teamId;
      ruleForm.acceptanceTime = row.acceptanceTime;
      ruleForm.maintenanceTime = row.maintenanceTime;
      ruleForm.id = row.id;

      let articleArr = []
      articleBuilds.list.forEach(item => {
        row.articleBuilds.forEach(i => {
          if (item.article.id == i.articleId) {
            console.log(item);

            articleArr.push(i.articleId)
            item.article.flag = true;
            item.id = i.id;
            item.build = i.buildIds;
          }
        })
      })
      console.log(articleArr);

      nextTick(() => {
        articleIdsRef.value.setCheckedKeys(articleArr);
        // buildIdsRef.value.setCheckedKeys(row.buildIds);
      });
      // ruleForm.articleIds = row.articleIds;
      // ruleForm.buildIds = row.buildIds;
    }
  })
  console.log(row);
  // console.log(row.articleIds, row.buildIds);

  // let keys = row.articleIds;
  // if (keys.length == articleIdsList.value.length) {
  //   articleIndeterminate.value = false;
  //   articleAll.value = true
  // } else if (keys.length) {
  //   articleAll.value = false
  //   articleIndeterminate.value = true;
  // } else {
  //   articleAll.value = false
  //   articleIndeterminate.value = false;
  // }

};
// 取消添加员工
const cancelAdd = () => {
  // ruleForm.articleIds = [];
  // ruleForm.buildIds = [];
  nextTick(() => {
    articleIdsRef.value.setCheckedKeys([]);
    buildIdsRef.value.setCheckedKeys([]);
  });
  ruleFormRef.value.resetFields();
  addDialogVisible.value = false;
};
// 确认添加员工
const submitAdd = async (formEl) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (dialongTitle.value == "添加员工") {
        // 如果身份为 线下人员（4），做出以下判断
        let data = {}
        if (ruleForm.userzzId == 4) {
          data = {
            userName: ruleForm.userName, // 名字
            userZzid: ruleForm.userzzId, // 身份Id
            schoolId: ruleForm.schoolId, // 校区Id
            workType: ruleForm.workType, // 工作Id
            teamId: ruleForm.teamId      // 维修班Id
          }
        } else {
          let arr = []
          articleBuilds.list.forEach(item => {
            if (item.article.flag && item.build.length != 0) {
              arr.push({
                articleId: item.article.id,
                buildIds: item.build
              })
            }
          })
          data = {
            userName: ruleForm.userName,
            cardNumber: ruleForm.cardNumber,
            userZzid: ruleForm.userzzId,
            userPhone: ruleForm.userPhone,
            schoolId: ruleForm.schoolId,
            teamId: ruleForm.teamId,
            workType: ruleForm.workType,
            // articleIds: ruleForm.articleIds,
            // buildIds: ruleForm.buildIds,
            acceptanceAssessTime: ruleForm.acceptanceTime,
            maintenanceAssessTime: ruleForm.maintenanceTime,
            articleBuilds: arr
          };
        }
        console.log(data, "添加员工数据");

        let res = await axios({
          method: "post",
          url: api.value + "/repairUser/insertRepairUserSetting",
          headers: {
            token: sessionStorage.getItem("token"),
            user_head: sessionStorage.getItem("userhead"),
          },
          data: data,
        });
        console.log(res, "添加员工");
        if (res.data.code == 200) {
          getList();
          ElMessage({
            type: "success",
            showClose: true,
            message: res.data.message,
            center: true,
          });
          // ruleForm.articleIds = [];
          // ruleForm.buildIds = [];
          nextTick(() => {
            articleIdsRef.value.setCheckedKeys([]);
            buildIdsRef.value.setCheckedKeys([]);
          });
          addDialogVisible.value = false;
          ruleFormRef.value.resetFields();
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      } else {
        // 如果身份为 线下人员（4），做出以下判断
        let data = {}
        if (ruleForm.userzzId == 4) {
          data = {
            userName: ruleForm.userName, // 名字
            userZzid: ruleForm.userzzId, // 身份Id
            schoolId: ruleForm.schoolId, // 校区Id
            workType: ruleForm.workType, // 工作Id
            teamId: ruleForm.teamId,     // 维修班Id
            id: ruleForm.id              // 数据ID
          }
        } else {
          let arr = []
          articleBuilds.list.forEach(item => {
            if (item.article.flag && item.build.length != 0) {
              arr.push({
                articleId: item.article.id,
                buildIds: item.build,
                id: item.id
              })
            }
          })
          data = {
            userName: ruleForm.userName,
            cardNumber: ruleForm.cardNumber,
            userZzid: ruleForm.userzzId,
            userPhone: ruleForm.userPhone,
            schoolId: ruleForm.schoolId,
            workType: ruleForm.workType,
            articleIds: ruleForm.articleIds,
            buildIds: ruleForm.buildIds,
            teamId: ruleForm.teamId,
            acceptanceAssessTime: ruleForm.acceptanceTime,
            maintenanceAssessTime: ruleForm.maintenanceTime,
            id: ruleForm.id,
            articleBuilds: arr
          };
        }
        console.log(data, "修改员工数据");
        let res = await axios({
          method: "post",
          url: api.value + "/repairUser/updateRepairUserSettingById",
          headers: {
            token: sessionStorage.getItem("token"),
            user_head: sessionStorage.getItem("userhead"),
          },
          data: data,
        });
        console.log(res, "编辑员工");
        if (res.data.code == 200) {
          getList();
          ElMessage({
            type: "success",
            showClose: true,
            message: res.data.message,
            center: true,
          });
          // ruleForm.articleIds = [];
          // ruleForm.buildIds = [];
          nextTick(() => {
            articleIdsRef.value.setCheckedKeys([]);
            buildIdsRef.value.setCheckedKeys([]);
          });
          addDialogVisible.value = false;
          ruleFormRef.value.resetFields();
        } else {
          ElMessage({
            type: "error",
            showClose: true,
            message: res.data.message,
            center: true,
          });
        }
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

//删除按钮
const del = async (row) => {
  let data = {
    id: row.id,
  };
  let res = await axios({
    method: "get",
    url: api.value + "/repairUser/deleteRepairUserSettingById",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: data,
  });
  if (res.data.code == 200) {
    if (tableData.list.length == 1 && currentPage.value != 1) {
      currentPage.value = currentPage.value - 1;
    }
    getList();
    ElMessage({
      type: "success",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
  console.log(res);
};

// 多选框功能
const handleSelectionChange = (val) => {
  console.log(val);
  selectData.list = val;
};
//导出功能
const importExcel = async () => {
  if (searchInput.createTime == null) {
    searchInput.createTime = "";
  }
  let data = new FormData();
  data.set("car_number", searchInput.carnumber);
  data.set("create_time", searchInput.createTime);
  let res = await axios({
    method: "post",
    url: api.value + "/carBook/cinfotoExcel.action",
    headers: {
      token: sessionStorage.getItem("token"),
    },
    data: data,
  });
  // console.log(res, "导出账号");
  if (res.data.code == 200) {
    // const elt = document.createElement("a");
    // elt.setAttribute(
    //   "href",
    //   "https://chtech.ncjti.edu.cn/carstop" + res.data.downurl
    // );
    // elt.setAttribute("download", "file.png");
    // elt.style.display = "none";
    // document.body.appendChild(elt);
    // elt.click();
    var downloadPath = "https://chtech.ncjti.edu.cn/carstop" + res.data.downurl;
    console.log("获得地址数据:", downloadPath);
    var downloadLink = document.createElement("a");
    downloadLink.style.display = "none"; // 使其隐藏
    downloadLink.href = downloadPath;
    downloadLink.download = "";
    downloadLink.click();
    document.body.appendChild(downloadLink);
    document.body.removeChild(downloadLink);
    ElMessage({
      type: "success",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};
// 表格斑马纹颜色修改
const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex % 2 === 0) {
    return "even";
  } else if (rowIndex % 2 !== 0) {
    return "odd";
  }
  return "";
};
// 分页
const handleCurrentChange = (value) => {
  // console.log(value);
  currentPage.value = value;
  getList();
};

onBeforeMount(async () => {
  api.value = store.state.user.api;
  //  查询身份下拉数据(--------)
  let res = await axios({
    method: "get",
    url: api.value + "/repairWorkType/getRepaairIdentitys",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
  });
  console.log(res, "查询身份下拉数据");
  userzzIdsList.value = res.data.data;

  //  查询工种下拉数据(-----------)
  let ress = await axios({
    method: "get",
    url: api.value + "/repairWorkType/getRepairWorkTypes",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
  });
  console.log(ress, "查询工种下拉数据");
  workTypeList.value = ress.data.data;

  // treeValueList(1) // 调用黄家湖 种类和楼栋 数据
  // treeValueList(2) // 调用墨轩湖 种类和楼栋 数据
  getList();
});
onUnmounted(() => {
  // document.removeEventListener("keyup", Enters);
});
</script>

<style scoped lang="scss">
.content-box {
  width: 97.5%;
  height: 89%;
  margin: 20px auto;
  background-color: #fff;
  color: #fff;
  display: flex;
  flex-direction: column;
  box-shadow: 0px 3px 10px rgba(213, 228, 252, 1);

  .left {
    // width: calc(100wh - 40px);
    display: flex;
    align-items: center;
    height: 60px;
    margin: 0 30px;
    border-bottom: 1px solid #ccc;
    color: rgb(0, 0, 0);
    font-size: 18px;
    font-weight: 600;

    span {
      margin-right: 20px;
      cursor: pointer;
    }

    .is_active {
      color: rgba(111, 182, 184, 1);
    }
  }

  .middle {
    width: 96%;
    margin: 0 auto;

    color: #000;

    // border-bottom: 1px solid rgb(231, 231, 231);
    .filter {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      margin: 10px 0 0 0;

      .search {
        color: #fff;
      }

      .condition {
        display: flex;
        align-items: center;
        margin: 10px 30px 10px 0;

        :deep(.el-input .el-input__inner) {
          font-size: 16px;
        }

        span {
          margin: 0 10px 0 0;
        }
      }
    }

    .gongneng {
      margin: 10px 0 20px 0;

      span {
        color: #fff;
      }
    }

    :deep(.cont) {
      width: 60%;
      margin: 20px auto;
    }

    :deep(.download) {
      display: flex;
      align-items: center;
      margin: 10px;
    }

    :deep(.download span) {
      font-size: 16px;
      margin-left: 20px;
    }

    :deep(.cont .el-button) {
      margin-left: 60px;
      margin-bottom: 30px;
    }

    :deep(.cont .accomplish) {
      width: 100%;
      display: flex;
      justify-content: center;
    }

    :deep(.cont .accomplish .el-button) {
      width: 50%;
      margin: 0;
    }
  }

  .footer {
    width: 96%;
    height: 551px;
    margin: 10px auto 30px;

    .el-table--fit {
      height: 100%;

      :deep(.el-table__header-wrapper) {
        background-color: #000;
        font-size: 16px;

        tr {
          color: #000;
        }
      }

      :deep(.el-table__row) {
        height: 50px;
        font-size: 16px;
        color: #000;
      }

      :deep(.el-table__row):nth-child(2n) {
        .el-table-fixed-column--right {
          background-color: rgba(240, 243, 247, 1);
        }
      }

      :deep(.el-table__row td) {
        padding: 0;
        border: 0;
      }

      .el-button--primary {
        margin-left: 5px;
      }

      :deep(.el-table__body .even) {
        background-color: #fff;
      }

      :deep(.el-table__body .odd) {
        background-color: rgba(240, 243, 247, 1);
      }

      :deep(.edit) {
        display: flex;
        align-items: center;
        justify-content: center;
        color: rgba(111, 182, 184, 1);
      }

      :deep(.look) {
        padding: 0 10px;
        cursor: pointer;
      }

      :deep(.look):hover {
        color: red;
      }
    }

    // 添加员工弹窗样式
    :deep(.addStaff) {
      //   height: 420px;
      border-radius: 11px;

      .el-dialog__header {
        border-radius: 11px 11px 0 0;
        background: rgba(237, 241, 245, 1);
        font-weight: 600;
        margin: 0;

        .el-dialog__headerbtn {
          outline: none;
        }
      }

      .el-dialog__body {
        padding: 30px 20px 10px 20px;
        max-height: 700px;
        overflow: auto;

        .el-input {
          width: 200px;
        }

        // 关联报修类型样式（-----------------）
        .checkbox {



          .el-form-item__content {
            // width: 200px;
            // display: flex;
            // flex-direction: column;
            // align-items: flex-start;
            // border: 1px solid red;

            .type {
              display: flex;

              .articleType {
                padding-right: 30px;

                .el-tree {
                  .el-tree-node__content {
                    .el-icon {
                      display: none;
                    }
                  }

                  .custom-tree-node {
                    display: flex;
                    align-items: center;

                    img {
                      width: 18px;
                      margin-left: 5px;
                    }
                  }
                }
              }

              .buildType {
                .allAriticle {
                  margin-left: 24px;
                }
              }
            }

            .articleTitle {
              font-weight: 600;
            }



          }
        }

        .options {
          .el-form-item__content {
            .queding {
              margin-left: 20px;
              color: #fff;
            }

            display: flex;
            flex-direction: row-reverse;
          }
        }
      }
    }
  }

  .pageSize {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 0 30px;

    span {
      color: #000;
    }

    .el-pagination {

      // width: 1600px;
      :deep(.el-pagination__total) {
        color: #000;
      }

      :deep(.el-pagination__goto) {
        color: #000;
      }

      :deep(.el-pagination__classifier) {
        color: #000;
      }

      :deep(.el-input__wrapper) {
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        box-shadow: none;
      }

      :deep(.el-pager li) {
        margin: 0 5px;
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        background-color: transparent;
      }

      :deep(.el-pager li.is-active) {
        background-color: rgba(111, 182, 184, 1);
      }

      :deep(.btn-prev) {
        margin-right: 5px;
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        background-color: transparent;
      }

      :deep(.btn-next) {
        margin-left: 5px;
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        background-color: transparent;
      }
    }
  }
}

.el-input {
  width: 192px;
}
</style>
