<template>
  <el-skeleton :rows="30" :loading="pageBasicsData.loading" />
  <!-- 指派任务 -->
  <div class="task-box" v-if="!pageBasicsData.loading">
    <qu-search-area ref="topSearchRef" :model="pageBasicsData.screenForm" @search="queryScreen" @reset="resetScreen">
          <el-form-item prop="dateType">
            <el-select
              style="width: 110px"
              filterable
              placeholder="请选择"
              v-model="pageBasicsData.screenForm.dateType"
            >
              <el-option
                v-for="item in pageBasicsData.dateTypeList"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="date" style="margin-left: -20px">
            <qu-time-select v-model.date="pageBasicsData.screenForm.date" />
          </el-form-item>
          <el-form-item label="所属站点" prop="districtId">
            <div class="screen-item">
              <el-select
                filterable
                placeholder="请选择"
                v-model="pageBasicsData.screenForm.districtId"
              >
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="item in pageBasicsData.districtList"
                  :key="item.id"
                ></el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="任务名称" prop="taskName">
            <div class="screen-item">
              <el-input
                placeholder="请输入任务名称"
                clearable
                v-model="pageBasicsData.screenForm.taskName"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item label="任务场景" prop="taskScene">
            <el-cascader
              ref="taskSceneRef"
              clearable
              :show-all-levels="false"
              collapse-tags
              v-model="pageBasicsData.screenForm.taskScene"
              :options="pageBasicsData.searchTaskSceneOptions"
              :props="{
                multiple: true,
                children: 'childNode',
                label: 'name',
                value: 'gridId',
                emitPath: false,
                checkStrictly: true,
              }"
              @change="handleTaskSceneChange(1)"
            />
          </el-form-item>
          <el-form-item label="任务描述" prop="taskContent">
            <div class="screen-item">
              <el-input
                placeholder="请输入任务描述"
                clearable
                v-model="pageBasicsData.screenForm.taskContent"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item label="计划状态" prop="status">
            <div class="screen-item">
              <el-select
                filterable
                clearable
                placeholder="请选择计划状态"
                v-model="pageBasicsData.screenForm.status"
              >
                <el-option
                  v-for="item in pageBasicsData.statusList"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                ></el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="任务执行人员" prop="userName">
            <div class="screen-item">
              <el-select
                filterable
                clearable
                placeholder="请选择"
                v-model="pageBasicsData.screenForm.userName"
              >
                <el-option
                  :label="item.name"
                  :value="item.name"
                  v-for="item in pageBasicsData.userNameList"
                  :key="item.id"
                ></el-option>
              </el-select>
            </div>
          </el-form-item>
    </qu-search-area>
    <!-- 表格 -->
    <div class="main-table">
      <qu-table
        :custom="true"
        :showPage="true"
        :showIndex="true"
        :showOverflowTooltip="true"
        :height="pageBasicsData.tableHeight"
        :tableData="tableData"
        :tableHeader="tableHeader"
        :pageProps="pageProps"
        @pageChange="pageChange"
        :rowButtons="rowButtons"
        @rowButtonClick="rowButtonClick"
        @fetchTableAttr="fetchTableAttr"
        :tableButtons="[
          { cnName: '新建', enName: 'add', theme: 'success', icon: 'plus' },
          { cnName: '导出', enName: 'export', theme: 'primary', icon: 'top' },
        ]"
        @buttonClick="buttonClick"
      />
    </div>
    <el-dialog
      title="新建"
      width="640px"
      v-model="addRelevant.openAddDialog"
      @close="closeAddDialog"
    >
      <el-form
        style="border-top: 1px solid #dcdfe6; border-bottom: 1px solid #dcdfe6"
        label-width="130px"
        ref="addTaskRef"
        :model="addRelevant.addFrom"
      >
        <el-divider content-position="left">在哪做？</el-divider>
        <el-form-item
          label="所属站点"
          prop="districtId"
          :rules="{
            required: true,
            message: '请选择所属站点',
            trigger: 'change',
          }"
        >
          <el-select
            style="width: 350px"
            filterable
            placeholder="请选择所属站点"
            v-model="addRelevant.addFrom.districtId"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in pageBasicsData.districtList"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务场景" prop="taskScene">
          <el-cascader
            style="width: 350px"
            ref="taskSceneRef"
            clearable
            :show-all-levels="false"
            v-model="addRelevant.addFrom.taskScene"
            :options="addRelevant.addTaskSceneOptions"
            :props="{
              multiple: true,
              children: 'childNode',
              label: 'name',
              value: 'gridId',
              emitPath: false,
              checkStrictly: true,
            }"
            @change="handleTaskSceneChange(2)"
          />
        </el-form-item>
        <el-divider content-position="left">做什么？</el-divider>
        <el-form-item
          label="任务名称"
          prop="taskName"
          :rules="{
            required: true,
            message: '请输入任务名称',
            trigger: 'change',
          }"
        >
          <el-input
            v-model="addRelevant.addFrom.taskName"
            style="width: 350px"
            maxlength="13"
            placeholder="请输入任务名称"
            show-word-limit
          />
        </el-form-item>
        <el-form-item
          label="任务描述"
          prop="taskContent"
          :rules="{
            required: true,
            message: '请输入任务描述',
            trigger: 'change',
          }"
        >
          <el-input
            v-model="addRelevant.addFrom.taskContent"
            style="width: 350px"
            type="textarea"
            autosize
            maxlength="500"
            placeholder="请输入备注信息(非必填,限1000字以内)"
            show-word-limit
          />
        </el-form-item>
        <el-divider content-position="left">哪天做？</el-divider>
        <el-form-item
          label="任务开始时间"
          prop="actionTimeType"
          :rules="{
            required: true,
            message: '请选择任务开始时间',
            trigger: 'change',
          }"
        >
          <el-radio-group v-model="addRelevant.addFrom.actionTimeType">
            <el-radio :label="0" style="margin-right: 16px">立刻</el-radio>
            <el-radio :label="1">预约</el-radio>
          </el-radio-group>
          <el-form-item
            v-if="addRelevant.addFrom.actionTimeType == 1"
            class="start-time"
            prop="startTime"
            :rules="[
              {
                required: true,
                message: '选择日期时间',
                trigger: 'change',
              },
              {
                validator: checkReleaseTime,
              },
            ]"
          >
            <el-date-picker
              style="width: 210px; margin-left: 20px"
              v-model="addRelevant.addFrom.startTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              :disabledDate="disabledDateFun"
              :default-time="new Date(2000, 1, 1, 23, 59, 59)"
            />
          </el-form-item>
        </el-form-item>
        <el-form-item label="期待完成时间" prop="endTime">
          <el-date-picker
            style="width: 350px"
            v-model="addRelevant.addFrom.endTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabledDate="disabledDateFun"
            :default-time="new Date(2000, 1, 1, 23, 59, 59)"
            placeholder="请选择期待完成时间"
          />
        </el-form-item>
        <el-divider content-position="left">谁来做？</el-divider>
        <el-form-item
          label="任务执行人员"
          prop="userType"
          :rules="{
            required: true,
            message: '请选择任务执行人员',
            trigger: 'change',
          }"
        >
          <el-select
            style="width: 350px"
            filterable
            placeholder="请选择任务执行人员"
            v-model="addRelevant.addFrom.userType"
          >
            <el-option
              :label="item.value"
              :value="item.key"
              v-for="item in [
                { key: 1, value: '选择任务执行人员' },
                { key: 2, value: '选择任务执行班组' },
              ]"
              :key="item.key"
            ></el-option>
          </el-select>
          <el-button
            :type="!addRelevant.addFrom.userType ? 'info' : 'success'"
            size="small"
            round
            :disabled="!addRelevant.addFrom.userType"
            style="margin-left: 5px"
            @click="goSelectPrincipal"
            >去选择
          </el-button>
        </el-form-item>
        <el-form-item
          label=""
          prop="executeStaff"
          v-if="
            addRelevant.addFrom.executeStaff?.length &&
            addRelevant.addFrom.userType == 1
          "
        >
          <template
            v-for="item in addRelevant.addFrom.executeStaff"
            :key="item.id"
          >
            <el-tag
              type="danger"
              size="small"
              effect="dark"
              style="margin-right: 5px"
            >
              {{ item.userNames }}
            </el-tag>
          </template>
        </el-form-item>
        <el-form-item
          label=""
          prop="teamPerson"
          v-if="
            addRelevant.addFrom.teamPerson?.length &&
            addRelevant.addFrom.userType == 2
          "
        >
          <template
            v-for="item in addRelevant.addFrom.teamPerson"
            :key="item.id"
          >
            <el-tag
              type="danger"
              size="small"
              effect="dark"
              style="margin-right: 5px"
            >
              {{ item.workGroupName }}
            </el-tag>
          </template>
        </el-form-item>
        <el-form-item label="时薪类型" prop="wageId">
          <el-select
            style="width: 350px"
            filterable
            clearable
            placeholder="请选择"
            v-model="addRelevant.addFrom.wageId"
          >
            <el-option
              v-for="item in pageBasicsData.wageHourList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="设定工时"
          prop="wageHour"
          :rules="[
            {
              required: true,
              message: '请输入设定工时',
              trigger: 'change',
            },
            {
              validator: verifyWageHour,
            },
          ]"
          v-if="addRelevant.addFrom.wageId"
        >
          <el-input
            v-model="addRelevant.addFrom.wageHour"
            style="width: 350px"
            placeholder=""
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="计划状态" prop="status">
          <el-select
            style="width: 350px"
            filterable
            clearable
            placeholder="请选择"
            v-model="addRelevant.addFrom.status"
          >
            <el-option
              v-for="item in pageBasicsData.addOrEditTaskStatus"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            style="width: 90px"
            @click="addRelevant.openAddDialog = false"
            >取消</el-button
          >
          <el-button style="width: 90px" type="primary" @click="addSubmitForm"
            >提交</el-button
          >
        </span>
      </template>
    </el-dialog>
    <!-- 编辑弹窗 -->
    <el-dialog
      title="编辑"
      width="640px"
      v-model="editRelevant.openEditDialog"
      @close="closeEditDialog"
    >
      <el-form
        style="border-top: 1px solid #dcdfe6; border-bottom: 1px solid #dcdfe6"
        label-width="130px"
        ref="editTaskRef"
        :model="editRelevant.editFrom"
      >
        <el-divider content-position="left">在哪做？</el-divider>
        <el-form-item
          label="所属站点"
          prop="districtId"
          :rules="{
            required: true,
            message: '请选择所属站点',
            trigger: 'change',
          }"
        >
          <el-select
            style="width: 350px"
            filterable
            disabled
            placeholder="请选择所属站点"
            v-model="editRelevant.editFrom.districtId"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              v-for="item in pageBasicsData.districtList"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务场景" prop="taskScene">
          <el-cascader
            style="width: 350px"
            ref="taskSceneRef"
            clearable
            :show-all-levels="false"
            v-model="editRelevant.editFrom.taskScene"
            :options="editRelevant.editTaskSceneOptions"
            :props="{
              multiple: true,
              children: 'childNode',
              label: 'name',
              value: 'id',
              emitPath: false,
              checkStrictly: true,
            }"
            @change="handleTaskSceneChange(3)"
          />
        </el-form-item>
        <el-divider content-position="left">做什么？</el-divider>
        <el-form-item
          label="任务名称"
          prop="taskName"
          :rules="{
            required: true,
            message: '请输入任务名称',
            trigger: 'change',
          }"
        >
          <el-input
            v-model="editRelevant.editFrom.taskName"
            style="width: 350px"
            maxlength="13"
            placeholder="请输入任务名称"
            show-word-limit
          />
        </el-form-item>
        <el-form-item
          label="任务描述"
          prop="taskContent"
          :rules="{
            required: true,
            message: '请输入任务描述',
            trigger: 'change',
          }"
        >
          <el-input
            v-model="editRelevant.editFrom.taskContent"
            style="width: 350px"
            type="textarea"
            autosize
            maxlength="500"
            placeholder="请输入备注信息(非必填,限500字以内)"
            show-word-limit
          />
        </el-form-item>
        <el-divider content-position="left">哪天做？</el-divider>
        <el-form-item
          label="任务开始时间"
          prop="startTime"
          :rules="[
            {
              required: true,
              message: '选择日期时间',
              trigger: 'change',
            },
            {
              validator: checkReleaseTime,
            },
          ]"
        >
          <el-date-picker
            style="width: 350px"
            v-model="editRelevant.editFrom.startTime"
            placeholder="请选择任务开始时间"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="new Date(2000, 1, 1, 23, 59, 59)"
            :disabledDate="disabledDateFun"
          />
        </el-form-item>
        <el-form-item label="期待完成时间" prop="endTime">
          <el-date-picker
            style="width: 350px"
            v-model="editRelevant.editFrom.endTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择期待完成时间"
          />
        </el-form-item>
        <el-divider content-position="left">谁来做？</el-divider>

        <el-form-item
          label="任务执行人员"
          prop="userType"
          :rules="{
            required: true,
            message: '请选择任务执行人员',
            trigger: 'change',
          }"
        >
          <el-select
            style="width: 350px"
            filterable
            placeholder="请选择所属站点"
            v-model="editRelevant.editFrom.userType"
          >
            <el-option
              :label="item.value"
              :value="item.key"
              v-for="item in [
                { key: 1, value: '选择任务执行人员' },
                { key: 2, value: '选择任务执行班组' },
              ]"
              :key="item.key"
            ></el-option>
          </el-select>
          <el-button
            :type="!editRelevant.editFrom.userType ? 'info' : 'success'"
            size="small"
            round
            :disabled="!editRelevant.editFrom.userType"
            style="margin-left: 5px"
            @click="pageBasicsData.showSelectPrincipal = true"
            >去选择
          </el-button>
        </el-form-item>
        <el-form-item
          label=""
          prop="workMember"
          v-if="
            editRelevant.editFrom.executeStaff?.length &&
            editRelevant.editFrom.userType == 1
          "
        >
          <template
            v-for="item in editRelevant.editFrom.executeStaff"
            :key="item.id"
          >
            <el-tag
              type="danger"
              size="small"
              effect="dark"
              style="margin-right: 5px"
            >
              {{ item.userNames }}
            </el-tag>
          </template>
        </el-form-item>
        <el-form-item
          label=""
          prop="workMember"
          v-if="
            editRelevant.editFrom.teamPerson?.length &&
            editRelevant.editFrom.userType == 2
          "
        >
          <template
            v-for="item in editRelevant.editFrom.teamPerson"
            :key="item.id"
          >
            <el-tag
              type="danger"
              size="small"
              effect="dark"
              style="margin-right: 5px"
            >
              {{ item.workGroupName }}
            </el-tag>
          </template>
        </el-form-item>
        <el-form-item label="时薪类型" prop="wageId">
          <el-select
            style="width: 350px"
            filterable
            clearable
            placeholder="请选择"
            v-model="editRelevant.editFrom.wageId"
          >
            <el-option
              v-for="item in pageBasicsData.wageHourList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="设定工时"
          prop="wageHour"
          :rules="[
            {
              required: true,
              message: '请输入设定工时',
              trigger: 'change',
            },
            {
              validator: verifyWageHour,
            },
          ]"
          v-if="editRelevant.editFrom.wageId"
        >
          <el-input
            v-model="editRelevant.editFrom.wageHour"
            style="width: 350px"
            placeholder=""
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            style="width: 90px"
            @click="editRelevant.openEditDialog = false"
            >取消</el-button
          >
          <el-button
            style="width: 90px"
            type="info"
            disabled
            v-if="
              editRelevant.editFrom.status == 2 ||
              new Date(editRelevant.editFrom.startTime).getTime() <
                new Date().getTime()
            "
            @click="editSubmitForm"
            >提交</el-button
          >
          <el-button
            v-else
            style="width: 90px"
            type="primary"
            @click="editSubmitForm"
            >提交</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 任务状态设置弹窗 -->
    <el-dialog
      v-model="pageBasicsData.showTaskStateSet"
      title="任务状态设置"
      width="600px"
    >
      <el-form :model="setPlanStatusForm">
        <div
          style="display: flex; align-items: center; justify-content: center"
        >
          <el-form-item label="计划状态" prop="status">
            <el-select
              style="width: 350px"
              filterable
              clearable
              placeholder="请选择"
              v-model="setPlanStatusForm.status"
            >
              <el-option
                v-for="item in setPlanStatusForm.planStateList"
                :key="item.key"
                :label="item.value"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            style="width: 90px"
            @click="pageBasicsData.showTaskStateSet = false"
            >取消</el-button
          >
          <el-button style="width: 90px" type="primary" @click="taskStateSubmit"
            >提交</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 选择负责人 -->
    <div v-if="pageBasicsData.showSelectPrincipal">
      <el-dialog
        v-model="pageBasicsData.showSelectPrincipal"
        title="选择任务执行人员"
        fullscreen
      >
        <selectExecuteStaffCom
          @closePrincipalDialog="closePrincipalDialog"
          @closeTempDialog="closeTempDialog"
          :userType="
            pageBasicsData.relevant
              ? addRelevant.addFrom.userType
              : editRelevant.editFrom.userType
          "
          :districtId="
            pageBasicsData.relevant
              ? addRelevant.addFrom.districtId
              : editRelevant.editFrom.districtId
          "
          :selectedPersonnel="
            pageBasicsData.relevant
              ? addRelevant.addFrom.executeStaff
              : editRelevant.editFrom.executeStaff
          "
          :selectedTeam="
            pageBasicsData.relevant
              ? addRelevant.addFrom.teamPerson
              : editRelevant.editFrom.teamPerson
          "
        />
      </el-dialog>
    </div>
  </div>

   <!-- 优先级设置弹窗 start-->
   <div v-if="showPrioritySet">
    <el-dialog title="优先级设置" width="500px" v-model="showPrioritySet">
      <prioritySetCom
        v-model:updateShowPrioritySet="showPrioritySet"
        :currentRow="editRelevant.editFrom"
        @confirmSubmit="handlerPrioritySet"
      />
    </el-dialog>
  </div>
  <!-- 优先级设置弹窗 end-->
</template>
<script setup>
import { ref, reactive, onMounted, watch, nextTick } from "vue";
import templateHooks from "@/Hooks/templateHooks.js";
import selectExecuteStaffCom from "@/Components/taskCenter/selectExecuteStaffCom.vue";
import { assignTaskService,setPlanTaskOrderService } from "@/ApiService/taskCenterService";
import { dropdownService } from "@/ApiService/dropdownService";
import prioritySetCom from "@/Components/taskCenter/taskSet/prioritySetCom.vue";
//页面基础数据
const pageBasicsData = reactive({
  loading: true, // 页面加载状态
  tableHeight: 200, //表格高度
  screenForm: {
    // 顶部搜索字段
    type: 2,
    dateType: 0,
    date: [],
    districtId: "",
    taskName: "",
    taskScene: "",
    taskContent: "",
    status: "",
    userName: "",
  },
  districtList: [], // 所属站点列表
  searchTaskSceneOptions: [], // 搜索时任务场景
  dateTypeList: [
    // 时间类型下拉列表
    {
      key: 0,
      value: "创建日期",
    },
    {
      key: 1,
      value: "开始日期",
    },
    {
      key: 2,
      value: "期待完成日期",
    },
  ],
  statusList: [
    // 任务状态下拉列表
    {
      key: 0,
      value: "启用",
    },
    {
      key: 1,
      value: "停用",
    },
    {
      key: 2,
      value: "结束",
    },
  ],
  addOrEditTaskStatus: [
    {
      key: 0,
      value: "启用",
    },
    {
      key: 1,
      value: "停用",
    },
  ],
  wageHourList: [], // 时薪类型
  userNameList: [], // 任务执行人员下拉列表
  showSelectPrincipal: false, // 选择负责人弹窗
  showTaskStateSet: false, // 任务状态设置弹窗
  relevant: true,
});

// 元素ref
const topSearchRef = ref(); // 顶部搜索区域
const taskSceneRef = ref(); // 任务场景
const screenFormRef = ref(); // 搜索区
const addTaskRef = ref();
const editTaskRef = ref();
// 任务状态设置
const setPlanStatusForm = reactive({
  status: 0,
  planStateList: [
    {
      key: 0,
      value: "启用",
    },
    {
      key: 1,
      value: "停用",
    },
  ],
});
// 新增任务
const addRelevant = reactive({
  openAddDialog: false,
  addTaskSceneOptions: [],
  addFrom: {
    districtId: "",
    taskScene: [],
    scenes: [],
    taskName: "",
    taskContent: "",
    actionTimeType: 0,
    startTime: "",
    endTime: "",
    executeStaff: [],
    teamPerson: [],
    userIds: [],
    status: 0,
    type: 2,
    wageId: "",
    wageHour: "",
    userType: "",
  },
});
// 编辑任务
const editRelevant = reactive({
  openEditDialog: false,
  editTaskSceneOptions: [],
  editFrom: {
    taskScene: [],
    scenes: [],
    executeStaff: [],
    teamPerson: [],
    userIds: [],
    workGroupIds: [],
    type: 2,
    wageId: "",
    wageHour: "",
  },
});
const showPrioritySet = ref(false); // 优先级设置弹窗
//#region watch定义start
// 设置表格高度
watch(
  () => topSearchRef.value,
  (val) => {
    let wHeight =
      document.documentElement.clientHeight || document.body.clientHeight;
    nextTick(() => {
      pageBasicsData.tableHeight = wHeight - val.clientHeight - 184;
    });
  }
);
// 站点变化清空其它查询条件
watch(
  () => pageBasicsData.screenForm.districtId,
  (val) => {
    if (val) {
      for (const key in pageBasicsData.screenForm) {
        if (key !== "districtId" && key !== "dateType" && key !== "type") {
          pageBasicsData.screenForm[key] = "";
        }
      }
      fetchTaskScene(val, "search");
      fetchTaskPerson(val);
    }
  }
);
watch(
  () => addRelevant.addFrom.districtId,
  (val) => {
    if (val) {
      fetchTaskScene(val, "addTask");
      fetchWageType(val);
    }
  }
);
watch(
  () => editRelevant.editFrom.districtId,
  (val) => {
    if (val) {
      fetchTaskScene(val, "editTask");
      fetchWageType(val);
    }
  }
);
watch(
  () => addRelevant.addFrom.actionTimeType,
  (val) => {
    if (val == 0) {
      addRelevant.addFrom.startTime = "";
      addRelevant.addFrom.endTime = "";
    }
  }
);
//#endregion watch定义end

// 生命周期
onMounted(() => {
  //获取站点数据
  fetchDistricts();
  buttonsClickFun.data = {
    // 编辑
    edit: () => {
      pageBasicsData.relevant = false;
      if (editRelevant.editFrom.userType == 1) {
        checkedPlanUserList();
      } else {
        checkedTeamList();
      }
      editRelevant.editFrom.taskScene = [];
      if (editRelevant.editFrom.scenesList?.length > 0) {
        editRelevant.editFrom.scenesList.forEach((item) => {
          editRelevant.editFrom.taskScene.push(item.id);
        });
      }
      editRelevant.openEditDialog = true;
    },
    // 删除
    delete: () => {
      $messageBox
        .confirm("此操作将永久删除该数据，是否继续？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
        .then(() => {
          assignTaskService
            .removePlan({
              id: editRelevant.editFrom.id,
            })
            .then((res) => {
              if (res.code == 0) {
                $message.success(res.data);
                fetchData();
              } else {
                $message.error(res.err);
              }
            });
        })
        .catch(() => {});
    },
    stateSet: () => {
      if (editRelevant.editFrom.status == 2) {
        return $message.warning("当前任务状态不可进行修改!");
      }
      if (
        new Date(editRelevant.editFrom.startTime).getTime() <
        new Date().getTime()
      ) {
        return $message.warning("计划任务已派发,不可进行修改!");
      }
      pageBasicsData.showTaskStateSet = true;
    },
    prioritySet: () => {
      // 优先级设置
      showPrioritySet.value = true;
    },
  };
});
//#region 函数定义start
// 顶部按钮事件
const buttonClick = ({ enName }) => {
  if (enName == "add") {
    pageBasicsData.wageHourList = [];
    addRelevant.addFrom.userType = "";
    pageBasicsData.relevant = true;
    addRelevant.openAddDialog = true;
  }
  if (enName == "export") {
    const { page, rows } = pageProps;
    assignTaskService.planAppointExport({
      page,
      rows,
      ...pageBasicsData.screenForm,
    });
  }
};
// 优先级设置
const handlerPrioritySet = (data) => {
  console.log(data);
  setPlanTaskOrderService
    .setPlanTaskOrder({
      ...data
    })
    .then((res) => {
      console.log(res);
      if (res.code == 0) {
        fetchData();
        $message.success(res.data);
        showPrioritySet.value = false;
      } else {
        $message.error(res.err);
      }
    });
};
// 添加任务提交
const addSubmitForm = () => {
  if (
    addRelevant.addFrom.userType == 1 &&
    addRelevant.addFrom.executeStaff?.length <= 0
  ) {
    return $message.warning("请选择任务执行人员!");
  } else if (
    addRelevant.addFrom.userType == 2 &&
    addRelevant.addFrom.teamPerson?.length <= 0
  ) {
    return $message.warning("请选择任务执行班组!");
  }
  // 立刻时期待完成时间验证规则
  if (addRelevant.addFrom.endTime) {
    let newStartTime = addRelevant.addFrom.startTime
      ? new Date(addRelevant.addFrom.startTime)
      : new Date();
    let newEndTime = new Date(addRelevant.addFrom.endTime);
    if (newEndTime.getTime() <= newStartTime.getTime()) {
      return $message.warning("期待完成时间必须大于开始时间!");
    }
  }
  addTaskRef.value.validate((valid) => {
    if (valid) {
      $messageBox
        .confirm("您确定要进行提交吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
        .then(() => {
          addRelevant.addFrom.userIds = [];
          if (addRelevant.addFrom.executeStaff.length) {
            addRelevant.addFrom.executeStaff.forEach((item) => {
              addRelevant.addFrom.userIds.push(item.id);
            });
          }
          addRelevant.addFrom.workGroupIds = [];
          if (addRelevant.addFrom.teamPerson.length) {
            addRelevant.addFrom.teamPerson.forEach((item) => {
              addRelevant.addFrom.workGroupIds.push(item.workGroupId);
            });
          }
          if (addRelevant.addFrom.userType) {
            if (addRelevant.addFrom.userType == 1) {
              addRelevant.addFrom.workGroupIds = [];
            } else {
              addRelevant.addFrom.userIds = [];
            }
          }

          let {
            districtId,
            taskName,
            taskContent,
            actionTimeType,
            startTime,
            endTime,
            userIds,
            status,
            scenes,
            type,
            userType,
            workGroupIds,
            wageId,
            wageHour,
          } = addRelevant.addFrom;
          assignTaskService
            .addOrUpdateAppointPlan({
              districtId,
              taskName,
              taskContent,
              actionTimeType,
              startTime,
              endTime,
              userIds,
              status,
              scenes,
              type,
              isCross: scenes?.length > 0 ? 1 : 0,
              userType,
              workGroupIds,
              wageId,
              wageHour,
            })
            .then((res) => {
              if (res.code == 0) {
                $message.success(res.data);
                closeAddDialog();
                fetchData();
              } else {
                $message.error(res.err);
              }
            });
        })
        .catch(() => {});
    }
  });
};
// 添加弹窗关闭事件
const closeAddDialog = () => {
  addRelevant.openAddDialog = false;
  pageBasicsData.relevant = true;
  addTaskRef.value.resetFields();
  addRelevant.addFrom.userIds = [];
  addRelevant.addFrom.workGroupIds = [];
  addRelevant.addFrom.scenes = [];
  addRelevant.addFrom.executeStaff = [];
  addRelevant.addFrom.teamPerson = [];
};
// 编辑表单提交
const editSubmitForm = () => {
  if (
    editRelevant.editFrom.userType == 1 &&
    editRelevant.editFrom.executeStaff?.length <= 0
  ) {
    return $message.warning("请选择任务执行人员!");
  } else if (
    editRelevant.editFrom.userType == 2 &&
    editRelevant.editFrom.teamPerson?.length <= 0
  ) {
    return $message.warning("请选择任务执行班组!");
  }
  // 期待完成时间验证规则
  if (editRelevant.editFrom.endTime) {
    let newStartTime = editRelevant.editFrom.startTime
      ? new Date(editRelevant.editFrom.startTime)
      : new Date();
    let newEndTime = new Date(editRelevant.editFrom.endTime);
    if (newEndTime.getTime() <= newStartTime.getTime()) {
      return $message.warning("期待完成时间必须大于开始时间!");
    }
  }
  editTaskRef.value.validate((valid) => {
    if (valid) {
      $messageBox
        .confirm("您确定要进行提交吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        })
        .then(() => {
          editRelevant.editFrom.userIds = [];
          if (editRelevant.editFrom.executeStaff?.length > 0) {
            editRelevant.editFrom.executeStaff.forEach((item) => {
              editRelevant.editFrom.userIds.push(item.id);
            });
          }
          editRelevant.editFrom.workGroupIds = [];
          if (editRelevant.editFrom.teamPerson?.length > 0) {
            editRelevant.editFrom.teamPerson.forEach((item) => {
              editRelevant.editFrom.workGroupIds.push(item.workGroupId);
            });
          }
          if (editRelevant.editFrom.userType == 0) {
            editRelevant.editFrom.workGroupIds = [];
            editRelevant.editFrom.userIds = [];
          }
          if (editRelevant.editFrom.userType) {
            if (editRelevant.editFrom.userType == 1) {
              editRelevant.editFrom.workGroupIds = [];
            } else {
              editRelevant.editFrom.userIds = [];
            }
          }
          let newScenesList = [];
          if (editRelevant.editFrom.scenesList?.length > 0) {
            editRelevant.editFrom.scenesList.forEach((item) => {
              newScenesList.push({
                id: item.sceneId ? item.sceneId : item.gridId,
                isscene: item.isscene,
                level: item.level,
                name: item.name,
              });
            });
          }
          if (editRelevant.editFrom.scenes?.length <= 0) {
            editRelevant.editFrom.scenes = newScenesList;
          }
          let {
            id,
            districtId,
            taskName,
            taskContent,
            actionTimeType,
            startTime,
            endTime,
            userIds,
            scenes,
            type,
            userType,
            workGroupIds,
            wageId,
            wageHour,
          } = editRelevant.editFrom;
          assignTaskService
            .addOrUpdateAppointPlan({
              id,
              districtId,
              taskName,
              taskContent,
              actionTimeType,
              startTime,
              endTime,
              userIds,
              scenes,
              type,
              isCross: scenes?.length > 0 ? 1 : 0,
              userType,
              workGroupIds,
              wageId,
              wageHour,
            })
            .then((res) => {
              if (res.code == 0) {
                $message.success("编辑成功");
                closeEditDialog();
                fetchData();
              } else {
                $message.error(res.err);
              }
            });
        })
        .catch(() => {});
    }
  });
};
const closeEditDialog = () => {
  editRelevant.openEditDialog = false;
  pageBasicsData.relevant = false;
  editTaskRef.value.resetFields();
  editRelevant.editFrom.userIds = [];
  editRelevant.editFrom.executeStaff = [];
  editRelevant.editFrom.teamPerson = [];
  editRelevant.editFrom.scenes = [];
};
const goSelectPrincipal = () => {
  if (!addRelevant.addFrom.districtId) {
    return $message.warning("请选择所属站点后再进行操作!");
  }
  pageBasicsData.showSelectPrincipal = true;
};
// 禁用时间设置
const disabledDateFun = (time) => {
  return time.getTime() < Date.now() - 8.64e7;
};
// 开始时间验证规则
const checkReleaseTime = (rule, value, callback) => {
  var date = new Date(value);
  if (date.getTime() < Date.now()) {
    callback(new Error(" 任务开始时间必须大于当前时间!"));
  } else {
    callback();
  }
};
// 自定义工时校验规则
const verifyWageHour = (rule, value, callback) => {
  if (value) {
    value = value.toString();
    if (isNaN(Number(value))) {
      callback(new Error("工时必须为数字值!"));
    } else if (Number(value) <= 0) {
      callback(new Error("工时不能小于0!"));
    } else if (value.indexOf(".") > 0) {
      let index = value.indexOf(".");
      let str = value.slice(index + 1);
      if (str && str.length > 2) {
        callback(new Error("小数点后只能输入两位!"));
      } else {
        callback();
      }
    } else {
      callback();
    }
  } else {
    callback(new Error("请输入设定工时!"));
  }
};
// 任务状态设置
const taskStateSubmit = () => {
  $messageBox
    .confirm("您确定要进行提交吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      center: true,
    })
    .then(() => {
      assignTaskService
        .setPlanStatus({
          districtId: editRelevant.editFrom.districtId,
          id: editRelevant.editFrom.id,
          status: setPlanStatusForm.status,
        })
        .then((res) => {
          if (res.code == 0) {
            $message.success(res.data);
            fetchData();
            pageBasicsData.showTaskStateSet = false;
          } else {
            $message.error(res.err);
          }
        });
    })
    .catch(() => {});
};
// 已选中计划人员
const checkedPlanUserList = () => {
  return new Promise(() => {
    assignTaskService
      .getPlanUserList({ planId: editRelevant.editFrom.id })
      .then(async (res) => {
        if (res.code == 0) {
          res.data.forEach((item) => {
            editRelevant.editFrom.executeStaff.push({
              id: item.userId,
              userNames: item.name,
              mobile: item.mobile,
            });
          });
        }
      });
  });
};
// 已选中计划班组
const checkedTeamList = () => {
  return new Promise(() => {
    assignTaskService
      .getPlanWorkGroupList({ planId: editRelevant.editFrom.id })
      .then(async (res) => {
        if (res.code == 0) {
          res.data.forEach((item) => {
            editRelevant.editFrom.teamPerson.push({
              workGroupId: item.workGroupId,
              workGroupName: item.workGroupName,
              principalUserName: item.principalUserName,
              userNames: item.userNames,
            });
          });
        }
      });
  });
};
// 关闭任务执行班组弹窗
const closeTempDialog = (value, type) => {
  let checkTeam = [];
  if (value?.length) {
    value.forEach((item) => {
      checkTeam.push({
        workGroupId: item.workGroupId,
        workGroupName: item.workGroupName,
        principalUserName: item.principalUserName,
        userNames: item.userNames,
      });
    });
    if (pageBasicsData.relevant) {
      addRelevant.addFrom.teamPerson = checkTeam;
    } else {
      editRelevant.editFrom.teamPerson = checkTeam;
    }
  } else {
    addRelevant.addFrom.teamPerson = [];
    editRelevant.editFrom.teamPerson = [];
  }
  addRelevant.addFrom.userType = type;
  editRelevant.editFrom.userType = type;
  pageBasicsData.showSelectPrincipal = false;
};
// 关闭任务执行人员弹窗
const closePrincipalDialog = (value, type) => {
  let checkedStaffList = [];
  if (value?.length) {
    value.forEach((item) => {
      checkedStaffList.push({
        id: item.id,
        userNames: item.userNames,
        mobile: item.mobile,
      });
    });
    if (pageBasicsData.relevant) {
      addRelevant.addFrom.executeStaff = checkedStaffList;
    } else {
      editRelevant.editFrom.executeStaff = checkedStaffList;
    }
  } else {
    addRelevant.addFrom.executeStaff = [];
    editRelevant.editFrom.executeStaff = [];
  }
  addRelevant.addFrom.userType = type;
  editRelevant.editFrom.userType = type;
  pageBasicsData.showSelectPrincipal = false;
};
// 获取列表数据
const fetchData = () => {
  setDateFormat();
  const { page, rows } = pageProps;
  return new Promise(() => {
    assignTaskService
      .planPageList({
        page,
        rows,
        ...pageBasicsData.screenForm,
      })
      .then((res) => {
        if (res.code == 0) {
          pageBasicsData.loading = false;
          tableData.value = res.data.rows;
          pageProps.records = res.data.records;
        }
      });
  });
};
// 设置查询日期格式
const setDateFormat = () => {
  for (const key in pageBasicsData.screenForm) {
    if (key.indexOf("Time") > -1) {
      delete pageBasicsData.screenForm[key];
    }
  }
  let dateArr = pageBasicsData.screenForm.date;
  if (pageBasicsData.screenForm.dateType == 0) {
    // 创建日期
    pageBasicsData.screenForm.createTimeStart = dateArr[0];
    pageBasicsData.screenForm.createTimeEnd = dateArr[1];
  } else if (pageBasicsData.screenForm.dateType == 1) {
    // 开始日期
    pageBasicsData.screenForm.startTimeStart = dateArr[0];
    pageBasicsData.screenForm.startTimeEnd = dateArr[1];
  } else if (pageBasicsData.screenForm.dateType == 2) {
    // 期待完成日期
    pageBasicsData.screenForm.endTimeStart = dateArr[0];
    pageBasicsData.screenForm.endTimeEnd = dateArr[1];
  }
};
// 任务场景级联事件
const handleTaskSceneChange = (value) => {
  let checkArr = taskSceneRef.value.getCheckedNodes();
  let scenes = [];
  checkArr.forEach((item) => {
    scenes.push({
      id: item.data.sceneId ? item.data.sceneId : item.data.gridId,
      isscene: item.data.isscene,
      level: item.data.level,
      name: item.data.name,
    });
  });
  if (value == 1) {
    pageBasicsData.screenForm.scenes = scenes;
  } else if (value == 2) {
    addRelevant.addFrom.scenes = scenes;
  } else if (value == 3) {
    editRelevant.editFrom.scenes = scenes;
  }
};
// 获取所属站点
const fetchDistricts = () => {
  return new Promise(() => {
    dropdownService.getDistrict().then(async (res) => {
      if (res.code == 0) {
        pageBasicsData.districtList = res.data;
        if (pageBasicsData.districtList?.length) {
          pageBasicsData.screenForm.districtId =
            pageBasicsData.districtList[0].id;
          fetchData();
        } else {
          $message.error("暂无站点信息,请配置站点!");
        }
      }
    });
  });
};
// 获取任务场景
const fetchTaskScene = (id, type) => {
  return new Promise(() => {
    dropdownService.gridSceneTree({ districtId: id }).then(async (res) => {
      if (res.code == 0) {
        if (type == "search") {
          pageBasicsData.searchTaskSceneOptions = res.data.childNode;
        } else if (type == "addTask") {
          addRelevant.addTaskSceneOptions = res.data.childNode;
        } else if (type == "editTask") {
          editRelevant.editTaskSceneOptions = res.data.childNode;
        }
      }
    });
  });
};
// 获取任务执行人员下拉
const fetchTaskPerson = (id) => {
  return new Promise(() => {
    dropdownService.principalList({ districtId: id }).then(async (res) => {
      pageBasicsData.userNameList = res.data;
    });
  });
};
// 获取时薪类型下拉
const fetchWageType = (id) => {
  console.log(id);
  return new Promise(() => {
    dropdownService.getDistrictWage({ districtId: id }).then((res) => {
      console.log(res);
      if (res.code == 0) {
        pageBasicsData.wageHourList = res.data;
      }
    });
  });
};
// 查询
const queryScreen = () => {
  pageProps.page = 1;
  fetchData();
};
// 重置
const resetScreen = () => {
  screenFormRef.value.resetFields();
  pageBasicsData.screenForm.districtId = pageBasicsData.districtList[0].id;
  fetchData();
};
// 自定义表格头
const fetchTableAttr = (tableAttr) => {
  tableHeader.value = tableAttr;
};
// 表格按钮
const rowButtonClick = ({ row, $column }) => {
  for (let i in row) {
    editRelevant.editFrom[i] = row[i];
  }
  if (editRelevant.editFrom.startTime) {
    editRelevant.editFrom.startTime = $common.fomatDateTime(
      editRelevant.editFrom.startTime
    );
  }
  if (editRelevant.editFrom.endTime) {
    editRelevant.editFrom.endTime = $common.fomatDateTime(
      editRelevant.editFrom.endTime
    );
  }

  buttonsClickFun.data[$column.enName]();
};
const {
  tableData,
  rowButtons,
  pageProps,
  tableHeader,
  pageChange,
  buttonsClickFun,
  $message,
  $messageBox,
  $common,
  selectItems,
} = templateHooks(fetchData);
//#endregion 函数定义 end
</script>
<script>
export default {
  name: "AssignTask",
};
</script>
<style lang="scss" scoped>
.task-box {
  box-sizing: border-box;
  height: calc(100vh - var(--page-top-offset));
  flex: 1;
  padding: 10px;
  background-color: var(--color-bg-card);
  .search-area {
    padding: var(--spacing-md) var(--spacing-lg);
    display: flex;
    align-items: center;
  }
}
.dialog-footer button:first-child {
  margin-right: 10px;
}

.dialog-item {
  width: 100%;
  display: flex;
  align-items: center;
  margin-left: 30px;
  .dialog-item-left {
    margin-right: 30px;
    div {
      margin-bottom: 30px;
    }
  }
  .dialog-item-right {
    .el-button {
      margin-bottom: 26px;
    }
  }
}
:deep(.el-upload-list__item-status-label) {
  position: absolute;
  right: -25px;
  top: 0;
  line-height: inherit;
}
:deep(.el-upload-list__item .el-icon--close) {
  position: absolute;
  top: 5px;
  right: -10px;
  cursor: pointer;
  opacity: 0.75;
  color: #292d3e;
}

.content-test {
  width: 200px;
  font-size: 14px;
  .btn {
    width: 30px;
    height: 30px;
  }
}
.start-time {
  :deep(.el-form-item__error) {
    left: 30px;
  }
}
</style>
