<template>
  <div class="app-container">
    <el-row :gutter="20" class="mb8">
      <el-col :span="8">
        <div class="table-button-group">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd(0)"
            v-hasPermi="['system:rules:add']"
            >设置值班人员
          </el-button>
          <div style="color: red; margin-top: 20px">
            备注：不区分白天、夜晚值班人员
          </div>
          <!-- 每班人数：
          <el-input-number
            v-model="woManNum"
            :min="1"
            :max="10"
            label="描述文字"
            size="small"
          ></el-input-number> -->
        </div>

        <div style="margin-top: 35px">
          <el-table
            class="draggable"
            min-height="400"
            max-height="400"
            border
            v-loading="loading"
            :data="woManUserList"
            style="float: left"
          >
            <!--<el-table-column type="selection" width="55" align="center" />-->
            <!--<el-table-column label="序号" align="center" prop="serialNum" />-->
            <el-table-column
              label="序号"
              width="55"
              align="center"
              type="index"
            ></el-table-column>
            <el-table-column label="值班人员" align="center" prop="userName" />
            <!-- <el-table-column label="性别" align="center" key="sex">
              <template #default="scope">
                {{ selectDictLabel(sys_user_sex, scope.row.sex) }}
              </template>
            </el-table-column> -->
            <el-table-column
              label="操作"
              width="160"
              align="center"
              prop="sex"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  icon="edit"
                  @click="editRowHandler(scope.row, scope.$index)"
                  >重选
                </el-button>
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="removeRowHandler(woManUserList, scope.$index)"
                  v-hasPermi="['system:rules:remove']"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="table-button-group">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd(1)"
            v-hasPermi="['system:rules:add']"
            >只值白班人员
          </el-button>
          <br />
          <div style="display: flex">
            <span style="margin-top: 5px">排序轮次：</span>
            <el-checkbox-group v-model="sortRound">
              <el-checkbox label="1">第一轮</el-checkbox>
              <el-checkbox label="2">第二轮</el-checkbox>
            </el-checkbox-group>
          </div>
          <div style="display: flex">
            <span style="margin-top: 5px">值班日期：</span>
            <el-checkbox-group v-model="dutyDateList">
              <el-checkbox label="6">周六</el-checkbox>
              <el-checkbox label="7">周日</el-checkbox>
              <el-checkbox label="0">节假日</el-checkbox></el-checkbox-group
            >
          </div>
          <div style="color: red; margin-top: 5px">
            备注：只值白班人员为排序第二轮开始每逢休息日（周六日、节假日）进行插入白天值班
          </div>
          <!-- 每班人数：
          <el-input-number
            v-model="manNum"
            :min="1"
            :max="10"
            label="描述文字"
            size="small"
          ></el-input-number> -->
        </div>
        <div>
          <el-table
            class="draggableMan"
            min-height="360.5"
            max-height="360.5"
            border
            v-loading="loading"
            :data="manUserList"
            style=""
          >
            <!--<el-table-column type="selection" width="55" align="center" />-->
            <!--<el-table-column label="序号" align="center" prop="serialNum" />-->
            <el-table-column
              label="序号"
              width="55"
              align="center"
              type="index"
            ></el-table-column>
            <el-table-column label="白班人员" align="center" prop="userName" />
            <!-- <el-table-column label="性别" align="center" key="sex">
              <template #default="scope">
                {{ selectDictLabel(sys_user_sex, scope.row.sex) }}
              </template>
            </el-table-column> -->
            <el-table-column
              label="操作"
              prop="sex"
              width="160"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  icon="edit"
                  @click="editRowHandler(scope.row, scope.$index)"
                  >重选
                </el-button>
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="removeRowHandler(manUserList, scope.$index)"
                  v-hasPermi="['system:rules:remove']"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="table-button-group">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd(2)"
            v-hasPermi="['system:rules:add']"
            >设置带班干部
          </el-button>
          <div style="color: red; margin-top: 74px"></div>
          <!-- 每班人数：
          <el-input-number
            v-model="manNum"
            :min="1"
            :max="10"
            label="描述文字"
            size="small"
          ></el-input-number> -->
        </div>
        <div>
          <el-table
            class="draggableLeader"
            min-height="400"
            max-height="400"
            border
            v-loading="loading"
            :data="leaderList"
            style=""
          >
            <!--<el-table-column type="selection" width="55" align="center" />-->
            <!--<el-table-column label="序号" align="center" prop="serialNum" />-->
            <el-table-column
              label="序号"
              width="55"
              align="center"
              type="index"
            ></el-table-column>
            <el-table-column label="带班干部" align="center" prop="userName" />
            <!-- <el-table-column label="性别" align="center" key="sex">
              <template #default="scope">
                {{ selectDictLabel(sys_user_sex, scope.row.sex) }}
              </template>
            </el-table-column> -->
            <el-table-column
              label="操作"
              prop="sex"
              width="160"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  icon="edit"
                  @click="editRowHandler(scope.row, scope.$index)"
                  >重选
                </el-button>
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="removeRowHandler(leaderList, scope.$index)"
                  v-hasPermi="['system:rules:remove']"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
  </div>
  <el-divider content-position="right"></el-divider>
  <span
    style="display: flex; justify-items: center; justify-content: center"
    class="dialog-footer"
  >
    <el-button @click="emit('cancel')">取 消</el-button>

    <el-button type="primary" @click="submitHandler">确 定</el-button>
  </span>
  <select-personnel
    v-if="open"
    :type="type"
    @select-change="selectPersonnelChange"
    :selected-list="[...woManUserList, ...manUserList, ...leaderList]"
    @submit="selectPersonnelSubmit"
    @canal="open = false"
  ></select-personnel>
  <edit-personnel
    v-if="open1"
    :sex="sex"
    :type="type"
    @select-change="selectPersonnelChange"
    :select-now="{ ...selectNow }"
    @submit1="selectPersonnelSubmitEdit"
    @canal="open1 = false"
  ></edit-personnel>
</template>

<script setup name="Rules">
import {
  listRules,
  getRules,
  delRules,
  addRules,
  updateRules,
  addList,
  lastAutomaticallyDuty,
  automaticallyDuty,
  toCheckExistDutyData,
} from "@/api/beOnDuty/dutyRules";
import { getCurrentInstance, onMounted } from "vue";
import Sortable from "sortablejs";
import { deptTreeSelect2, listUser } from "@/api/system/user";
import { addDateRange } from "@/utils/ruoyi";
import selectPersonnel from "@/views/components/user/selectPersonnel.vue";
import editPersonnel from "@/views/components/user/editPersonnel.vue";
import { ElMessage } from "element-plus";
const { proxy } = getCurrentInstance();

const nowList = ref([]);
const woManUserList = ref([]);
const manUserList = ref([]);
const leaderList = ref([]);
const sortRound = ref([]);
const dutyDateList = ref([]);
const open = ref(false);
const open1 = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dialogOr = ref("");
const type = ref("");
const title = ref("");
const indexEdit = ref(null);
const selection = ref([]);
// 部门
const deptOptions = ref([]);
const queryParams3 = ref({});
const selectNow = ref({});
const userList = ref([]);
const { sys_user_sex } = proxy.useDict("sys_user_sex");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    month: null,
    userId: null,
    userName: null,
    sex: null,
    serialNum: null,
    dutyNum: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

let woManNum = ref(2);
let manNum = ref(1);
let sex = ref(1);

let props = defineProps(["month"]);
const emit = defineEmits(["submit", "submit1", "dialogOr"]);

/*onMounted(() => {
  getList();
})*/
onMounted(() => {
  rowDrop();
  getNowMonthUserList();
});

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    month: null,
    userId: null,
    userName: null,
    sex: null,
    serialNum: null,
    dutyNum: null,
  };
  proxy.resetForm("rulesRef");
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function selectPersonnelChange(selection) {
  // console.log(selection);
  // ids.value = selection.map((item) => item.id);
  // single.value = selection.length != 1;
  // multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd(sexV) {
  if (sexV == 0) {
    nowList.value = woManUserList.value;
  } else if (sexV == 1) {
    nowList.value = manUserList.value;
  } else if (sexV == 2) {
    nowList.value = leaderList.value;
  }

  type.value = sexV;
  getDeptTree();
  handleQuery1();
  open.value = true;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getRules(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改值班规则";
  });
}

function removeDuplicates(data) {
  const userIds = data[0].userIds.split(",");
  const userNames = data[0].userName.split(",");
  const type = data[0].type;
  const userMap = new Map();

  // 只存储每个 userId 第一次出现时对应的 userName
  userIds.forEach((id, index) => {
    if (!userMap.has(id)) {
      userMap.set(id, userNames[index]);
    }
  });

  // 从 Map 中提取数据，保持插入顺序
  const uniqueUserIds = Array.from(userMap.keys()).join(",");
  const uniqueUserNames = Array.from(userMap.values()).join(",");

  return {
    userIds: uniqueUserIds,
    userName: uniqueUserNames,
    type: type,
  };
}

// 重选确定
function selectPersonnelSubmitEdit(selectUserListEdit) {
  console.log("selectUserListEdit111111", selectUserListEdit);
  console.log("type", type.value);
  let EditNew = removeDuplicates(selectUserListEdit);
  console.log("EditNew", EditNew);
  open1.value = false;
  if (type.value == 0) {
    woManUserList.value.splice(indexEdit.value, 1, EditNew);
  } else if (type.value == 1) {
    manUserList.value.splice(indexEdit.value, 1, EditNew);
  } else if (type.value == 2) {
    leaderList.value.splice(indexEdit.value, 1, EditNew);
  }

  // for (let user of selectionUserList) {
  //   user.userName = user.nickName;
  //   if (user.sex == 1) {
  //     woManUserList.value.push(user);
  //     continue;
  //   }
  //   manUserList.value.push(user);
  // }
  // woManUserList.value = unique(woManUserList.value);
  // manUserList.value = unique(manUserList.value);
}
/* 选择人员确定 */
function selectPersonnelSubmit(selectionUserList) {
  console.log("selectionUserList", selectionUserList);
  if (selectionUserList.length > 0) {
    open.value = false;
    if (type.value == 0) {
      woManUserList.value.push(selectionUserList[selectionUserList.length - 1]);
    } else if (type.value == 1) {
      console.log("manUserList.value", manUserList.value);
      manUserList.value.push(selectionUserList[selectionUserList.length - 1]);
    } else if (type.value == 2) {
      leaderList.value.push(selectionUserList[selectionUserList.length - 1]);
    }
  } else {
    ElMessage.error("请选择人员");
  }

  // for (let user of selectionUserList) {
  //   user.userName = user.nickName;
  //   if (user.sex == 1) {
  //     woManUserList.value.push(user);
  //     continue;
  //   }
  //   manUserList.value.push(user);
  // }
  // woManUserList.value = unique(woManUserList.value);
  // manUserList.value = unique(manUserList.value);
}

// 查询部门
async function getDeptTree() {
  const { data } = await deptTreeSelect2();
  deptOptions.value = data;
}

// 节点点击
function handleNodeClick(data) {
  queryParams3.value.deptId = data.id;
  handleQuery1();
}

function handleQuery1() {
  queryParams3.value.pageNum = 1;
  getList1();
}

async function getList1() {
  loading.value = true;
  let res = await listUser(addDateRange(queryParams3.value, []));
  loading.value = false;
  userList.value = res.rows;
  total.value = res.total;
}

//getList();

// 行拖拽
const rowDrop = function () {
  // 要拖拽元素的父容器 tbody
  const tbody = document.querySelector(
    ".draggable .el-table__body-wrapper tbody"
  );
  Sortable.create(tbody, {
    //  可被拖拽的子元素
    draggable: ".draggable .el-table__row",
    onEnd({ newIndex, oldIndex }) {
      // newIndex 拖动到的新的索引
      // oldIndex 没拖动前的索引
      const currRow = woManUserList.value.splice(oldIndex, 1)[0];
      woManUserList.value.splice(newIndex, 0, currRow);
      var temp = woManUserList.value;
      woManUserList.value = null;
      nextTick(() => {
        woManUserList.value = temp;
      });
    },
  });

  const draggableMan = document.querySelector(
    ".draggableMan .el-table__body-wrapper tbody"
  );
  Sortable.create(draggableMan, {
    //  可被拖拽的子元素
    draggable: ".draggableMan .el-table__row",
    onEnd({ newIndex, oldIndex }) {
      // newIndex 拖动到的新的索引
      // oldIndex 没拖动前的索引
      const currRow = manUserList.value.splice(oldIndex, 1)[0];
      manUserList.value.splice(newIndex, 0, currRow);
      var temp = manUserList.value;
      manUserList.value = null;
      nextTick(() => {
        manUserList.value = temp;
      });
    },
  });
  const draggableLeader = document.querySelector(
    ".draggableLeader .el-table__body-wrapper tbody"
  );
  Sortable.create(draggableLeader, {
    //  可被拖拽的子元素
    draggable: ".draggableLeader .el-table__row",
    onEnd({ newIndex, oldIndex }) {
      // newIndex 拖动到的新的索引
      // oldIndex 没拖动前的索引
      const currRow = leaderList.value.splice(oldIndex, 1)[0];
      leaderList.value.splice(newIndex, 0, currRow);
      var temp = leaderList.value;
      leaderList.value = null;
      nextTick(() => {
        leaderList.value = temp;
      });
    },
  });
};

function editRowHandler(row, index) {
  console.log("edit", row);
  indexEdit.value = index;
  open1.value = true;
  selectNow.value = row;
  type.value = row.type;
}
function removeRowHandler(list, index) {
  const currRow = list.splice(index, 1)[0];
}

/**
 * 获取本月
 * */
async function getNowMonthUserList() {
  let { rows } = await listRules();
  for (let user of rows) {
    if (user.type == 0) {
      woManUserList.value.push(user);
    } else if (user.type == 1) {
      console.log("user", user);
      if (user.wheel != undefined && user.wheel != null && user.wheel != "") {
        sortRound.value = user.wheel.split(",");
      }
      if (
        user.weekFlg != undefined &&
        user.weekFlg != null &&
        user.weekFlg != ""
      ) {
        dutyDateList.value = user.weekFlg.split(",");
      }

      manUserList.value.push(user);
    } else if (user.type == 2) {
      leaderList.value.push(user);
    }
  }
  // woManUserList.value = rows;
  // for (let user of rows) {
  //   user.nickName = user.userName;
  //   if (user.sex == 1) {
  //     woManUserList.value.push(user);
  //     continue;
  //   }
  //   // manUserList.value.push(user);
  // }
}

/**
 * 提交
 * */
async function submitHandler() {
  if (sortRound.value.length == 0) {
    proxy.$modal.msgError("请设置排序轮次");
    return;
  }
  proxy.$modal.loading("保存中");

  try {
    for (let ele of woManUserList.value) {
      // ele.dutyNum = woManNum;
      ele.type = 0;
    }
    for (let ele of manUserList.value) {
      ele.wheel = sortRound.value.join(",");
      ele.weekFlg = dutyDateList.value.join(",");
      // ele.dutyNum = manNum;
      ele.type = 1;
    }
    for (let ele of leaderList.value) {
      // ele.dutyNum = manNum;
      ele.type = 2;
    }
    console.log("manUserList", manUserList.value);
    let list = [
      ...woManUserList.value,
      ...manUserList.value,
      ...leaderList.value,
    ];

    // 保存并关闭
    for (let ele of list) {
      ele.month = props.month;
      //ele.userName = ele.nickName
    }
    console.log("list", list);
    let res = await addList(list);
    if (res.code == 200) {
      dialogOr.value = true;
      proxy.$modal.msgSuccess("保存成功");
      proxy.$modal.closeLoading();
    }
  } finally {
    proxy.$modal.closeLoading();
    emit("submit");
    emit("submit1");
    emit("dialogOr", dialogOr.value);
  }
}

// function unique(arr1) {
//   const res = new Map();
//   return arr1.filter(
//     (item) => !res.has(item.userId) && res.set(item.userId, 1)
//   );
// }

async function lastAutomaticallyDutyHandler() {
  proxy.$modal.loading("生成中...");
  try {
    await lastAutomaticallyDuty(props.month);
    getNowMonthUserList();
  } finally {
    proxy.$modal.closeLoading();
  }
}
</script>

<style>
.table-button-group {
  margin-top: 1rem;
  margin-bottom: 0.4rem;
}
.app-container {
  padding: 10px 20px;
}
</style>
