<template>
  <div>
    <el-tabs tab-position="left" class="demo-tabs" v-model="newUserType">
      <!-- 班组 -->
      <el-tab-pane label="选择班组" :name="2">
        <div>
          <div style="border-top: 1px solid #ccc; padding-top: 30px">
            <el-form ref="formRef" :model="teamSearchForm" inline>
              <el-form-item label="班组名称" prop="workGroupName">
                <el-input
                  placeholder="请输入班组名称"
                  clearable
                  v-model="teamSearchForm.workGroupName"
                ></el-input>
              </el-form-item>
              <el-form-item label="班组负责人" prop="principalUserName">
                <el-input
                  placeholder="请输入手机号"
                  clearable
                  v-model.number="teamSearchForm.principalUserName"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button
                  round
                  icon="Refresh"
                  type="warning"
                  @click="teamResetForm"
                  >清空</el-button
                >
                <el-button
                  type="primary"
                  icon="Search"
                  round
                  @click="teamRestSearch"
                  >搜索</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <!-- 表格 -->
          <div>
            <div class="principal-table">
              <div class="principal-left">
                <div class="principal-title">班组列表</div>
                <qu-table
                  :custom="false"
                  :showPage="true"
                  :height="400"
                  :tableData="teamPrincipalList"
                  :tableHeader="[
                    {
                      enName: 'workGroupName',
                      cnName: '班组名称',
                      isTableShow: true,
                    },
                    {
                      enName: 'principalUserName',
                      cnName: '班组负责人',
                      isTableShow: true,
                    },
                    {
                      enName: 'userNames',
                      cnName: '班组成员',
                      isTableShow: true,
                    },
                  ]"
                  :pageProps="pagePropsTeam"
                  @pageChange="pageChangeTeam"
                  :rowButtons="[
                    {
                      enName: 'add',
                      cnName: '选择负责人',
                      className: '',
                    },
                  ]"
                  @rowButtonClick="teamRowButtonClick"
                ></qu-table>
              </div>
              <div class="principal-right">
                <div class="principal-title">
                  已选班组 ({{ teamSelectWorkMember.length }})
                </div>
                <qu-table
                  ref="teamSelectWorkMemberRef"
                  :custom="false"
                  :showPage="false"
                  showSelect
                  :height="400"
                  :tableData="teamSelectWorkMember"
                  :tableHeader="[
                    {
                      enName: 'workGroupName',
                      cnName: '班组名称',
                      isTableShow: true,
                    },
                    {
                      enName: 'principalUserName',
                      cnName: '班组负责人',
                      isTableShow: true,
                    },
                  ]"
                  :pageProps="pageProps"
                  @pageChange="pageChange"
                  @selectionChange="teamTableChange"
                ></qu-table>
              </div>
            </div>

            <span
              style="
                height: 30px;
                display: flex;
                justify-content: center;
                margin-top: 30px;
              "
            >
              <el-button style="width: 90px" type="warning" @click="teamCancel"
                >取消</el-button
              >
              <el-button style="width: 90px" type="primary" @click="teamSubmit"
                >确定</el-button
              >
            </span>
          </div>
        </div>
      </el-tab-pane>

      <!-- 人员 -->
      <el-tab-pane label="选择人员" :name="1">
        <div>
          <div
            class="grid-right-search"
            style="border-top: 1px solid #ccc; padding-top: 30px"
          >
            <el-form ref="formRef" :model="searchForm" inline>
              <el-form-item label="姓名" prop="name">
                <el-input
                  placeholder="请输入姓名"
                  clearable
                  v-model="searchForm.name"
                ></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="mobile">
                <el-input
                  placeholder="请输入手机号"
                  clearable
                  v-model.number="searchForm.mobile"
                ></el-input>
              </el-form-item>
              <el-form-item label="账号角色类型" prop="approle">
                <el-select
                  v-model="searchForm.approle"
                  filterable
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    :label="item.value"
                    :value="item.key"
                    v-for="item in approleSelectList"
                    :key="item.key"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="系统权限类型" prop="roleType">
                <el-select
                  v-model="searchForm.roleType"
                  filterable
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    :label="item.value"
                    :value="item.key"
                    v-for="item in roleTypeSelectList"
                    :key="item.key"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="考勤状态" prop="workStatus">
                <el-select
                  v-model="searchForm.workStatus"
                  filterable
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    :label="item.value"
                    :value="item.key"
                    v-for="item in [
                      { key: 0, value: '上班' },
                      { key: 1, value: '下班' },
                      { key: 2, value: '请假' },
                      { key: 3, value: '休息' },
                    ]"
                    :key="item.key"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="工作状态" prop="workAtStatus">
                <el-select
                  v-model="searchForm.workAtStatus"
                  filterable
                  clearable
                  placeholder="请选择"
                >
                  <el-option
                    :label="item.value"
                    :value="item.key"
                    v-for="item in [
                      { key: 0, value: '作业' },
                      { key: 1, value: '转场' },
                      { key: 2, value: '空闲' },
                      { key: 3, value: '休息' },
                    ]"
                    :key="item.key"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button
                  round
                  icon="Refresh"
                  type="warning"
                  @click="personResetForm"
                  >清空</el-button
                >
                <el-button
                  type="primary"
                  icon="Search"
                  round
                  @click="personRestSearch"
                  >搜索</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <!-- 表格 -->
          <div>
            <div class="principal-table">
              <div class="principal-left">
                <div class="principal-title">人员列表</div>
                <qu-table
                  :custom="false"
                  :showPage="true"
                  :height="400"
                  :tableData="principalList"
                  :tableHeader="[
                    {
                      enName: 'userNames',
                      cnName: '姓名',
                      isTableShow: true,
                    },
                    {
                      enName: 'mobile',
                      cnName: '手机号',
                      isTableShow: true,
                    },
                    {
                      enName: 'workStatus',
                      cnName: '考勤状态',
                      isTableShow: true,
                    },
                    {
                      enName: 'workAtStatus',
                      cnName: '工作状态',
                      isTableShow: true,
                    },
                    {
                      enName: 'taskTotalCount',
                      cnName: '今日派工数量',
                      isTableShow: true,
                    },
                    {
                      enName: 'taskFinishCount',
                      cnName: '今日已完工数量',
                      isTableShow: true,
                    },
                    {
                      enName: 'taskworkCount',
                      cnName: '今日待完工数量',
                      isTableShow: true,
                    },
                    {
                      enName: 'approle',
                      cnName: '账号角色类型',
                      isTableShow: true,
                    },
                    {
                      enName: 'roleType',
                      cnName: '系统权限类型',
                      isTableShow: true,
                    },
                  ]"
                  :pageProps="pageProps"
                  @pageChange="pageChange"
                  :rowButtons="[
                    {
                      enName: 'add',
                      cnName: '选择负责人',
                      className: '',
                    },
                  ]"
                  @rowButtonClick="rowButtonClick"
                ></qu-table>
              </div>
              <div class="principal-right">
                <div class="principal-title">
                  已选人员 ({{ selectWorkMember.length }})
                </div>
                <qu-table
                  ref="selectWorkMemberRef"
                  :custom="false"
                  :showPage="false"
                  showSelect
                  :height="400"
                  :tableData="selectWorkMember"
                  :tableHeader="[
                    {
                      enName: 'userNames',
                      cnName: '姓名',
                      isTableShow: true,
                    },
                    {
                      enName: 'mobile',
                      cnName: '手机号',
                      isTableShow: true,
                    },
                  ]"
                  :pageProps="pageProps"
                  @pageChange="pageChange"
                  @selectionChange="tableChange"
                ></qu-table>
              </div>
            </div>

            <span
              style="
                height: 30px;
                display: flex;
                justify-content: center;
                margin-top: 30px;
              "
            >
              <el-button style="width: 90px" type="warning" @click="cancel"
                >取消</el-button
              >
              <el-button style="width: 90px" type="primary" @click="submit"
                >确定</el-button
              >
            </span>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, nextTick, watch, onBeforeUpdate } from "vue";
import { assignTaskService } from "@/ApiService/taskCenterService";
import templateHooks from "@/Hooks/templateHooks.js";

const props = defineProps({
  userType: {
    type: Number,
  },
  districtId: [Number, String],
  selectedPersonnel: {
    type: Array,
    default: () => [],
  },
  selectedTeam: {
    type: Array,
    default: () => [],
  },
});
const newUserType = ref(props.userType);
// 班组搜索字段
const teamSearchForm = reactive({
  workGroupName: "",
  principalUserName: "",
});
// 人员搜索字段
const searchForm = reactive({
  name: "",
  mobile: "",
  approle: "",
  roleType: "",
  workStatus: "",
  workAtStatus: "",
});
// 账号角色类型下拉列表
const approleSelectList = [
  {
    key: 2,
    value: "保洁",
  },
  {
    key: 5,
    value: "物业",
  },
];
// 权限型下拉列表
const roleTypeSelectList = [
  {
    key: 0,
    value: "管理权限",
  },
  {
    key: 1,
    value: "普通权限",
  },
];
const principalList = ref([]);
const teamPrincipalList = ref([]);
const selectWorkMember = ref([]);
const teamSelectWorkMember = ref([]);
const submitList = ref([]);
const teamSubmitList = ref([]);

const formRef = ref();
const selectWorkMemberRef = ref();
const teamSelectWorkMemberRef = ref();
const pagePropsTeam = reactive({
  page: 1,
  rows: 20,
  records: 0,
  sidx: "id",
  sord: "desc",
});
const $emits = defineEmits(["closePrincipalDialog", "closeTempDialog"]);

onMounted(() => {
  if (newUserType.value == 1) {
    if (props.selectedPersonnel?.length > 0) {
      props.selectedPersonnel.forEach((item) => {
        selectWorkMember.value.push(item);
      });
      nextTick(() => {
        setTimeout(() => {
          selectWorkMember.value.forEach((item) => {
            selectWorkMemberRef.value.toggleRowSelection(item, true);
          });
        }, 300);
      });
    }
    fetchData(props.districtId);
  } else {
    if (props.selectedTeam?.length > 0) {
      props.selectedTeam.forEach((item) => {
        teamSelectWorkMember.value.push(item);
      });
      nextTick(() => {
        setTimeout(() => {
          teamSelectWorkMember.value.forEach((item) => {
            teamSelectWorkMemberRef.value.toggleRowSelection(item, true);
          });
        }, 300);
      });
    }
    fetchTeamData(props.districtId);
  }
});
onBeforeUpdate(() => {
  if (newUserType.value == 1) {
    nextTick(() => {
      setTimeout(() => {
        selectWorkMember.value.forEach((item) => {
          selectWorkMemberRef.value.toggleRowSelection(item, true);
        });
      }, 300);
    });
  } else {
    nextTick(() => {
      setTimeout(() => {
        teamSelectWorkMember.value.forEach((item) => {
          teamSelectWorkMemberRef.value.toggleRowSelection(item, true);
        });
      }, 300);
    });
  }
});
watch(
  () => newUserType.value,
  (val) => {
    if (val == 1) {
      fetchData(props.districtId);
    } else {
      fetchTeamData(props.districtId);
    }
  }
);
// 选择班组逻辑
const teamRowButtonClick = ({ row }) => {
  let { workGroupName, workGroupId, userNames, principalUserName } = row;
  const key = teamSelectWorkMember.value.some(
    (item) => item.workGroupId == row.workGroupId
  );
  if (key) {
    $message.error("已选该班组,请勿重复选择!");
    return;
  }
  teamSelectWorkMember.value.push({
    workGroupName,
    principalUserName,
    workGroupId,
    userNames,
  });
  teamSelectWorkMemberRef.value.toggleRowSelection(
    teamSelectWorkMember.value[teamSelectWorkMember.value.length - 1],
    true
  );
};
// 选择人员逻辑
const rowButtonClick = ({ row }) => {
  let { id, userNames, mobile } = row;
  const key = selectWorkMember.value.some((item) => item.mobile == row.mobile);
  if (key) {
    $message.error("已选该人员,请勿重复选择!");
    return;
  }
  selectWorkMember.value.push({ id, userNames, mobile });
  selectWorkMemberRef.value.toggleRowSelection(
    selectWorkMember.value[selectWorkMember.value.length - 1],
    true
  );
};
const teamTableChange = (val) => {
  teamSubmitList.value = val;
};
const tableChange = (val) => {
  submitList.value = val;
};

// 人员表格数据
const fetchData = (id) => {
  return new Promise(() => {
    const { page, rows } = pageProps;
    assignTaskService
      .appointPlanUserList({
        rows,
        page,
        districtId: id || props.districtId,
        ...searchForm,
      })
      .then(async (res) => {
        if (res.code == 0) {
          let workStatusMap = ["上班", "下班", "请假", "休息"];
          let workAtStatusMap = ["作业", "转场", "空闲", "休息"];
          principalList.value = res.data.rows;
          principalList.value.map((item) => {
            approleSelectList.map((approle) => {
              if (approle.key == item.approle) {
                item.approle = approle.value;
              }
            });
            roleTypeSelectList.map((role) => {
              if (role.key == item.roleType) {
                item.roleType = role.value;
              }
            });
            item.workStatus = workStatusMap[item.workStatus];
            item.workAtStatus = workAtStatusMap[item.workAtStatus];
          });
          pageProps.records = res.data.records;
        }
      });
  });
};
// 班组表格数据
const fetchTeamData = (id) => {
  return new Promise(() => {
    const { page, rows } = pagePropsTeam;
    assignTaskService
      .getRoutinePlanWorkGroupList({
        rows,
        page,
        districtId: id || props.districtId,
        ...teamSearchForm,
      })
      .then(async (res) => {
        if (res.code == 0) {
          teamPrincipalList.value = res.data.rows;
          pagePropsTeam.records = res.data.records;
        }
      });
  });
};
// 班组提交
const teamSubmit = () => {
  $emits("closeTempDialog", teamSubmitList.value, newUserType.value);
};
// 班组取消
const teamCancel = () => {
  if (props.selectedTeam?.length > 0) {
    $emits("closeTempDialog", teamSubmitList.value, newUserType.value);
    selectWorkMemberRef.value.clearSelection();
  } else {
    $emits("closeTempDialog", [], newUserType.value);
  }
};
// 人员提交
const submit = () => {
  $emits("closePrincipalDialog", submitList.value, newUserType.value);
};
// 人员取消
const cancel = () => {
  if (props.selectedPersonnel?.length > 0) {
    $emits("closePrincipalDialog", submitList.value, newUserType.value);
    selectWorkMemberRef.value.clearSelection();
  } else {
    $emits("closePrincipalDialog", [], newUserType.value);
  }
};
// 班组搜索
const teamRestSearch = () => {
  pagePropsTeam.page = 1;
  fetchTeamData();
};
// 班组重置
const teamResetForm = () => {
  formRef.value.resetFields();
  fetchTeamData();
};
// 人员搜索
const personRestSearch = () => {
  pageProps.page = 1;
  fetchData();
};
// 人员重置
const personResetForm = () => {
  formRef.value.resetFields();
  fetchData();
};
const pageChangeTeam = ({ page, rows }) => {
  pagePropsTeam.rows = rows;
  pagePropsTeam.page = page;
  fetchTeamData();
};
const { pageProps, pageChange, $message } = templateHooks(fetchData);
</script>

<style lang="scss" scoped>
.principal-table {
  width: 100%;
  display: flex;
  box-sizing: border-box;
  border-top: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
  margin-top: 20px;
  padding-bottom: 20px;
  .principal-title {
    margin-top: 10px;
    margin-bottom: 10px;
    font-weight: bold;
    font-size: 16px;
  }
  .principal-left {
    width: calc(100% - 35%);
  }
  .principal-right {
    width: 35%;
    margin-left: 20px;
  }
}
.el-tabs--right .el-tabs__content,
.el-tabs--left .el-tabs__content {
  height: 100%;
}
</style>
