//巡逻规则管理
<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :inline="true" :model="page.data">
      <el-form-item class="margin-left input">
        <el-select
          filterable
          clearable
          v-model="page.data.positionId"
          placeholder="请选择巡逻点"
        >
          <el-option
            v-for="item in option1"
            :key="item.id"
            :label="item.positionName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="margin-left input">
        <el-input
          v-model="page.data.idName"
          placeholder="请输入姓名"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item class="margin-left input">
        <el-input
          v-model="page.data.idNumber"
          placeholder="请输入身份证号"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item class="margin-left">
        <el-button type="primary" @click="fetchData" icon="el-icon-search"
          >搜索</el-button
        >
      </el-form-item>
    </el-form>
    <div
      class="patrol-rules-content"
      v-for="(item, index) in tabData"
      :key="item.positionId"
    >
      <div class="top">
        <div class="title">
          <i
            class="el-icon-caret-top"
            v-if="!item.show"
            @click="item.show = !item.show"
          ></i>
          <i
            class="el-icon-caret-bottom"
            v-else
            @click="item.show = !item.show"
          ></i>
          <div class="title-num">{{ indexMethod(index) }}</div>
          <div class="titie-lib">{{ item.positionName }}</div>
          <div class="title-time">签到时间段数：{{ item.ruleCount }}</div>
        </div>
        <div>
          <el-button type="primary" size="small" @click="handleUpdate(item)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            size="small"
            @click="delRule(item.positionId)"
            >删除</el-button
          >
        </div>
      </div>
      <div>
        <el-collapse-transition>
          <div v-show="item.show">
            <el-table
              :data="item.ruleConfigs"
              v-loading="listLoading"
              border
              highlight-current-row
              class="table"
            >
              <el-table-column
                align="center"
                width="80"
                label="序号"
                type="index"
              >
              </el-table-column>
              <el-table-column align="center" label="签到时间段">
                <template slot-scope="scope">
                  {{ scope.row.startTime }}~{{ scope.row.endTime }}
                </template>
              </el-table-column>

              <el-table-column align="center" label="签到人员">
                <template slot-scope="scope">
                  {{ scope.row.idNames.map((t) => t).join("、") }}
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-collapse-transition>
      </div>
    </div>
    <div v-if="tabData.length == 0" class="box">
      <div class="el-table__empty-block" style="height: 100%; width: 1223px">
        <span class="el-table__empty-text">暂无数据</span>
      </div>
    </div>
    <!--分页栏-->
    <pagination
      :total="total"
      :page.sync="page.pageNumber"
      :limit.sync="page.pageSize"
      @pagination="fetchData"
    />
    <!-- 添加/编辑 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="870px"
      :close-on-click-modal="false"
    >
      <el-form
        :model="addOrUpdateForm"
        :rules="rules"
        ref="formRef"
        label-position="left"
        label-width="110px"
      >
        <div
          v-for="(item, index) in addOrUpdateForm.ruleConfigs"
          :key="item.key"
        >
          <el-row>
            <el-col :span="15">
              <el-form-item
                class="aaa"
                :prop="'ruleConfigs.' + index + '.time'"
                :label="`签到时间段${index + 1}`"
                :rules="{
                  required: true,
                  message: '请选择时间范围',
                  trigger: 'blur',
                }"
              >
                <el-time-picker
                  value-format="HH:mm:ss"
                  :editable="false"
                  is-range
                  v-model="item.time"
                  :default-value="[
                    new Date(0, 0, 0, 0, 0, 0),
                    new Date(0, 0, 0, 23, 0, 0),
                  ]"
                  range-separator="至"
                  start-placeholder="选择签到开始时间"
                  end-placeholder="选择签到结束时间"
                  placeholder="选择时间范围"
                >
                </el-time-picker>
              </el-form-item>
            </el-col>
            <el-col :span="3" :offset="6">
              <el-button
                icon="el-icon-close"
                circle
                @click="deleteProduct(item)"
                v-if="index"
              ></el-button>
              <el-button
                icon="el-icon-plus"
                circle
                @click="addProduct"
              ></el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item
                class="aaa"
                :prop="'ruleConfigs.' + index + '.userIds'"
                :label="`签到人员`"
                :rules="{
                  required: true,
                  message: '请选择签到人员',
                  trigger: 'blur',
                }"
              >
                <el-select
                  v-model="item.userIds"
                  filterable
                  multiple
                  clearable
                  placeholder="请选择签到人员"
                  @change="changeSelect(item)"
                >
                  <!-- :indeterminate="item.isIndeterminate" -->
                  <el-checkbox v-model="item.checked" @change="selectAll(item)"
                    >全选</el-checkbox
                  >
                  <el-option
                    v-for="item in option"
                    :key="item.id"
                    :label="item.idName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit" :loading="submitLoading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from "@/components/Pagination";
import { doGetRulelist, doEditRule, doDeleteRule } from "@/api/shoplist";
import { doGetPosition } from "@/api/orderRecord";
import { doGetSubuser } from "@/api/subuser";
export default {
  components: {
    Pagination,
  },
  data() {
    return {
      perviewImageVisible: false,
      dialogImageUrl: "",
      listLoading: false,
      submitLoading: false,
      isEdit: false, //判断是否是编辑
      total: 0,
      option1: [], //巡逻点列表
      option: [], //人员账号
      // 分页参数
      page: {
        data: {
          positionId: "",
          idName: "",
          idNumber: "",
        },
        pageNumber: 1,
        pageSize: 10,
      },
      tabData: [],
      tableData: [],
      // 标题
      dialogTitle: "",
      // 是否显示对话框
      dialogVisible: false,
      // 添加商品参数
      addOrUpdateForm: {
        positionId: "",
        ruleConfigs: [],
      },
      inputValue: "",
      rules: {},
    };
  },
  mounted() {
    this.fetchData();
    this.getSelectPosition();
    this.getSubUser();
  },
  methods: {
    fetchData() {
      this.listLoading = true;
      doGetRulelist(this.page).then((res) => {
        this.tabData = res.data.records.map((item) => {
          return { ...item, show: true };
        });
        this.total = res.data.total;
        this.listLoading = false;
      });
    },
    // 查询巡逻点
    getSelectPosition() {
      doGetPosition().then((res) => {
        this.option1 = res.data;
      });
    },
    getSubUser() {
      doGetSubuser().then((res) => {
        this.option = res.data;
      });
    },
    // 添加编辑
    handleUpdate(edit) {
      this.dialogTitle = "巡更规则 — " + edit.positionName;
      this.$refs.formRef?.clearValidate();
      const ruleConfigs = [
        {
          // time: ["00:00:00", "23:00:00"],
          time: "",
          userIds: [],
          key: new Date().getTime(),
          checked: false,
        },
      ];
      this.addOrUpdateForm = {
        positionId: edit.positionId,
        ruleConfigs: !!edit.ruleConfigs
          ? edit.ruleConfigs.map((item, index) => {
              const start = item.startTime;
              const end = item.endTime;
              return {
                time: [start, end],
                userIds: item.userIds,
                key: new Date().getTime() + index,
                checked: item.userIds.length == this.option.length,
                // isIndeterminate:
                //   item.userIds.length > 0 &&
                //   item.userIds.length < this.option.length,
              };
            })
          : ruleConfigs,
      };
      this.dialogVisible = true;
    },

    // 确认按钮
    submit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const ruleConfigs = this.addOrUpdateForm.ruleConfigs.map(
            (item, index) => {
              return {
                startTime: item.time[0],
                endTime: item.time[1],
                userIds: item.userIds,
                key: new Date().getTime() + index,
                index: index,
                checked: item.checked,
              };
            }
          );
          const sortedRuleConfigs = ruleConfigs.sort((a, b) => {
            const timeA = new Date(`1970-01-01T${a.startTime}`);
            const timeB = new Date(`1970-01-01T${b.startTime}`);
            return timeA - timeB;
          });
          // console.log(sortedRuleConfigs);
          // 打印按时间先后排序后的数组
          let isOverlap = false;
          for (let i = 1; i < sortedRuleConfigs.length; i++) {
            if (
              sortedRuleConfigs[i].startTime < sortedRuleConfigs[i - 1].endTime
            ) {
              isOverlap = true;
              this.$message({
                type: "error",
                message: `时间段${sortedRuleConfigs[i].index + 1}和时间段${
                  sortedRuleConfigs[i - 1].index + 1
                }有重叠!,请重新安排时间`,
              });
              break;
            }
          }
          if (!isOverlap) {
            // 时间段没有重叠，执行其他逻辑
            const params = {
              accountId: "",
              positionId: this.addOrUpdateForm.positionId,
              ruleConfigs: ruleConfigs,
            };
            doEditRule(params).then(() => {
              this.dialogVisible = false;
              this.fetchData();
              this.$message({
                type: "success",
                message: "编辑成功!",
              });
            });
          }
        }
      });
    },
    delRule(id) {
      this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).then(() => {
        doDeleteRule(id).then((res) => {
          this.fetchData();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        });
      });
    },
    // 全选
    selectAll(item) {
      item.userIds = [];
      if (item.checked) {
        this.option.map((v) => {
          item.userIds.push(v.id);
        });
      } else {
        item.userIds = [];
      }
    },
    changeSelect(val) {
      if (val.userIds.length === this.option.length) {
        val.checked = true;
      } else {
        val.checked = false;
      }
    },
    // 功能增加
    addProduct() {
      this.addOrUpdateForm.ruleConfigs.push({
        // time: ["00:00:00", "23:00:00"],
        time: "",
        userIds: [],
        key: new Date().getTime(),
        checked: false,
      });
    },
    //功能刪除
    deleteProduct(item) {
      let index = this.addOrUpdateForm.ruleConfigs.findIndex(
        (v) => v.key === item.key
      );
      if (index !== -1) {
        this.addOrUpdateForm.ruleConfigs.splice(index, 1);
      }
    },
    // 返回列表序号
    indexMethod(index) {
      return (this.page.pageNumber - 1) * this.page.pageSize + index + 1;
    },
  },
};
</script>

<style lang="scss" scoped>
.margin-left {
  margin: 10px 0 0 10px;
}
.input {
  width: 200px;
}
// 顶部样式
.top {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  .title {
    font-weight: 700;
    font-size: 18px;
    line-height: 27px;
    display: flex;
    align-items: center;
    color: #333;
    .title-num {
      margin-left: 10px;
      margin-right: 10px;
      width: 20px;
    }
    .titie-lib {
      width: 350px;
      margin-right: 10px;
    }
    .title-time {
      font-weight: 500;
      font-size: 14px;
    }
  }
}
.box {
  margin-top: 20px;
  border: 1px solid #ebeef5;
}
.el-checkbox {
  text-align: right;
  width: 100%;
  padding-right: 10px;
}
</style>
