<template>
  <div class="plan-task">
        <qu-search-area ref="topScreenRef" :model="screenForm" @search="restSearch" @reset="clearGridAndScreen">
            <el-form-item label="查询日期" prop="name">
              <el-date-picker v-model="screenForm.timeArr" type="datetimerange" range-separator="To"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
            <el-form-item label="所属站点" prop="districtId">
              <div class="screen-item">
                <district-screen v-model:districtId="screenForm.districtId" ref="districtScreenRef"
                  @districtChange="districtChange"></district-screen>
              </div>
            </el-form-item>
            <el-form-item label="网格" prop="gridCascader">
              <el-cascader
                ref="gridCascaderRef"
                v-model="gridCascaderValue"
                :options="treeData"
                :props="{
                  children: 'childNode',
                  label: 'name',
                  value: 'gridId',
                  checkStrictly: true,
                  emitPath: false,
                }"
                clearable
                filterable
                placeholder="请选择网格"
                style="width: 200px"
                @change="gridCascaderChange"
              />
            </el-form-item>
            <el-form-item label="任务名称" prop="taskName">
              <div class="screen-item">
                <el-input v-model="screenForm.taskName" placeholder="请输入任务名称" clearable></el-input>
              </div>
            </el-form-item>
            <el-form-item label="计划类型" prop="taskCreateType">
              <div class="screen-item">
                <el-select v-model="screenForm.taskCreateType" clearable>
                  <template v-for="(item, index) in selectItems['taskCreateType']" :key="index">
                    <el-option :label="item.value" :value="item.key"></el-option>
                  </template>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="重复方式" prop="circleStatus">
              <div class="screen-item">
                <el-select v-model="screenForm.circleStatus" clearable>
                  <template v-for="(item, index) in selectItems['circleStatus']" :key="index">
                    <el-option :label="item.value" :value="item.key"></el-option>
                  </template>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="计划状态" prop="status">
              <div class="screen-item">
                <el-select v-model="screenForm.status" clearable>
                  <template v-for="(item, index) in selectItems['status']" :key="index">
                    <el-option :label="item.value" :value="item.key"></el-option>
                  </template>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="任务场景" prop="sceneString">
              <div class="screen-item">
                <el-input v-model="screenForm.sceneString" placeholder="请输入任务场景" clearable></el-input>
              </div>
            </el-form-item>
            <el-form-item label="时薪类型" prop="wageId">
              <div class="screen-item">
                <el-select v-model="screenForm.wageId" clearable>
                  <template v-for="(item, index) in wageTypes" :key="index">
                    <el-option :label="item.name" :value="item.id"></el-option>
                  </template>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="是否合作任务" prop="userStatus">
              <div class="screen-item">
                <el-select v-model="screenForm.userStatus" clearable>
                  <template v-for="(item, index) in selectItems['userStatus']" :key="index">
                    <el-option :label="item.value" :value="item.key"></el-option>
                  </template>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="是否打包任务" prop="packageStatus">
              <div class="screen-item">
                <el-select v-model="screenForm.packageStatus" clearable>
                  <template v-for="(item, index) in selectItems['packageStatus']" :key="index">
                    <el-option :label="item.value" :value="item.key"></el-option>
                  </template>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="是否跨域派单" prop="isCross">
              <div class="screen-item">
                <el-select v-model="screenForm.isCross" clearable>
                  <template v-for="(item, index) in selectItems['isCross']" :key="index">
                    <el-option :label="item.value" :value="item.key"></el-option>
                  </template>
                </el-select>
              </div>
            </el-form-item>
        </qu-search-area>
        <el-skeleton :rows="10" v-if="!isLoaded" :throttle="500" />
        <div class="main-table" v-if="isLoaded">
          <qu-table :tableData="tableData" v-model:tableHeader="tableHeader" :height="tableHeight"
            :pageProps="pageProps" :rowButtons="rowButtons" @rowButtonClick="rowButtonClick" @pageChange="pageChange"
            @sortChange="sortChange" v-loading="tableLoading" :tableButtons="tableButtons" @buttonClick="buttonClick"></qu-table>
        </div>
        <!-- <div v-if="showAddForm"> -->
        <el-dialog :title="currentRow.data.id ? '编辑' : '新建'" v-model="showAddForm" fullscreen center
          @close="showAddForm = false">
          <div>
            <add-plan-task-form v-if="showAddForm" :currentRow="currentRow" :currentButton="currentButton"
              v-model:showAddForm="showAddForm" @OK="fetchData" ref="addFormRef"></add-plan-task-form>
          </div>
        </el-dialog>
        <!-- </div> -->
        <div v-if="showTaskStateSet">
          <el-dialog title="计划状态设置" v-model="showTaskStateSet" width="60%" center>
            <el-form>
              <el-form-item label="计划状态">
                <el-select v-model="taskStateSet" value-key="" placeholder="" clearable filterable>
                  <el-option label="启用" :value="0"></el-option>
                  <el-option label="停用" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="" size="default" @click="showTaskStateSet = false">取消</el-button>
                <el-button type="primary" size="default" @click="saveTaskStateSet">确定</el-button>
              </el-form-item>
            </el-form>
          </el-dialog>
        </div>
  </div>

  <!-- 优先级设置弹窗 start-->
  <div v-if="showPrioritySet">
    <el-dialog title="优先级设置" width="500px" v-model="showPrioritySet">
      <prioritySetCom
        v-model:updateShowPrioritySet="showPrioritySet"
        :currentRow="currentRow.data"
        @confirmSubmit="handlerPrioritySet"
      />
    </el-dialog>
  </div>
  <!-- 优先级设置弹窗 end-->

</template>
<script setup>
import { ref, reactive, onMounted, nextTick, watch } from "vue";
import templateHooks from "@/Hooks/templateHooks";
import { dropdownService } from "@/ApiService/dropdownService";
import {
  planTaskService,
  deviceTaskService,
  setPlanTaskOrderService
} from "@/ApiService/taskCenterService";
import addPlanTaskForm from "../../../../Components/taskCenter/taskSet/planTask/addPlanTaskFormCom.vue";
import prioritySetCom from "@/Components/taskCenter/taskSet/prioritySetCom.vue";

const isLoaded = ref(false);
const tableLoading = ref(false);
const treeData = ref([]);
const gridCascaderValue = ref(null);
const gridCascaderRef = ref();
const districtScreenRef = ref();
const tableHeight = ref(500);
const topScreenRef = ref();
const windowHeight = ref(0);
const showAddForm = ref(false);
const addFormRef = ref();
const taskTypes = ref([]);
const showTaskStateSet = ref(false);
const taskStateSet = ref();
const wageTypes = ref([])
const showPrioritySet = ref(false); // 优先级设置弹窗
// 数据定义 end
const buttonClick = (button) => {
  buttonsClickFun.data[button.enName]();
  currentButton.data = button;
  currentRow.data = {
    districtId: undefined,
    userType: 0, //任务执行人员类型
    startStatus: 0, //启用时间
    planEndDateType: 0, //截止时间
    circleStatus: 0, //重复 默认不重复
    circleType: 1,
    circleNo1: [],
    eliminateType: 0, //跳过日期
    userStatus: 0,
    taskCreateType: 0, //任务生成类型 默认定时定期
    actionTimeType: 0,
    expireTiming: 1, //任务过期天数 默认为1天
    actionCount: 1, //人流量数量 默认1
    status: 0, //计划状态 默认启用
    packageStatus: 0, //是否打包任务 默认否
    isCross: 0, //是否允许跨域派单
    workingTimingHour: 0,
    workingTimingMinute: 20,
    transitionTimingHour: 0,
    transitionTimingMinute: 15,
    readyTimingHour: 0,
    readyTimingMinute: 5,
    redundanceTimingHour: 0,
    redundanceTimingMinute: 5,
    wageId: null,
  };
};
// 优先级设置
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 rowButtonClick = ({ row, $column }) => {
  for (let i in row) {
    currentRow.data[i] = row[i];
  }
  getPlanListInfo().then((res) => {
    const { mustLabelIds, notLabelIds, objectIds, operationList } = res;
    currentRow.data.mustLabelIds = mustLabelIds;
    currentRow.data.notLabelIds = notLabelIds;
    currentRow.data.objectArr = objectIds;
    currentRow.data.selectedOperations = operationList;
  });
  let scenesArr = [];
  if (currentRow.data.scenesList) {
    scenesArr = Array.from(
      currentRow.data.scenesList,
      ({ sceneId }) => sceneId
    );
  }
  currentRow.data.scenesArr = scenesArr;

  // 获取任务执行人员
  // fetchMembers().then((res) => {
  //   currentRow.data.workMember = res;
  //   if (currentRow.data.workMember.length != 0) {
  //     currentRow.data.userType = 1;
  //   } else {
  //     fetchTeams().then((res) => {
  //       currentRow.data.workMember = res;
  //       if (currentRow.data.workMember.length != 0) {
  //         currentRow.data.userType = 2;
  //       }
  //     });
  //   }
  // });
  if (currentRow.data.userType == 1) {
    fetchMembers().then((res) => {
      currentRow.data.workMember = res;
    })
  } else if (currentRow.data.userType == 2) {
    fetchTeams().then((res) => {
      currentRow.data.workMember = res;

    });
  }

  // 任务执行时间
  // 开始时间
  if (currentRow.data.startTime) {
    currentRow.data.startTime = $common.fomatDateTime(
      currentRow.data.startTime
    );
  }
  // 截止时间
  if (currentRow.data.endTime) {
    currentRow.data.planEndDateType = 1;
    currentRow.data.endTime = $common.fomatDateTime(currentRow.data.endTime);
  } else {
    currentRow.data.planEndDateType = 0;
  }
  //执行周期
  if (currentRow.data.circleStatus == 1) {
    currentRow.data.circleNo1 = currentRow.data.circleNo.split(",").map(Number);
  } else if (currentRow.data.circleStatus == 2) {
    currentRow.data.circleNo2 = Number(currentRow.data.circleNo);
  }

  //要求执行时间段
  if (currentRow.data.actionTimeType == 1) {
    currentRow.data.timeArr = [
      currentRow.data.actionStartTime,
      currentRow.data.actionEndTime,
    ];
  }

  // 工时
  currentRow.data.workingTimingHour = parseInt(
    currentRow.data.workingTiming / 60
  );
  currentRow.data.workingTimingMinute = parseInt(
    currentRow.data.workingTiming % 60
  );
  currentRow.data.transitionTimingHour = parseInt(
    currentRow.data.transitionTiming / 60
  );
  currentRow.data.transitionTimingMinute = parseInt(
    currentRow.data.transitionTiming % 60
  );
  currentRow.data.readyTimingHour = parseInt(currentRow.data.readyTiming / 60);
  currentRow.data.readyTimingMinute = parseInt(
    currentRow.data.readyTiming % 60
  );
  currentRow.data.redundanceTimingHour = parseInt(
    currentRow.data.redundanceTiming / 60
  );
  currentRow.data.redundanceTimingMinute = parseInt(
    currentRow.data.redundanceTiming % 60
  );

  currentButton.data = $column;
  setTimeout(() => {
    buttonsClickFun.data[$column.enName]();
  }, 500);
};
const getPlanListInfo = () => {
  return new Promise((resolve) => {
    planTaskService
      .getPlanListInfo({ planId: currentRow.data.id })
      .then((res) => {
        if (res.code == 0) {
          resolve(res.data);
        } else {
          resolve({});
          $message.error(res.err);
        }
      });
  });
};
// 级联选择器变化
const gridCascaderChange = (val) => {
  if (!val) {
    screenForm.scenes = [];
    return;
  }
  const checkedNodes = gridCascaderRef.value?.getCheckedNodes();
  if (checkedNodes && checkedNodes.length > 0) {
    const nodeData = checkedNodes[0].data;
    const { sceneId, gridId, isscene, level, name } = nodeData;
    const id = isscene == 1 ? sceneId : gridId;
    screenForm.scenes = [{ isscene, level, name, id }];
  } else {
    screenForm.scenes = [];
  }
};
// 重置搜索（含网格级联）
const clearGridAndScreen = () => {
  gridCascaderValue.value = null;
  screenForm.scenes = [];
  clearScreen(screenFormRef, ['districtId']);
};
const fetchData = () => {
  const { page, rows, sord, sidx } = pageProps;
  if (screenForm.timeArr) {
    screenForm.startTimeStart = screenForm.timeArr[0];
    screenForm.startTimeEnd = screenForm.timeArr[1];
  }

  planTaskService
    .planPageList({ type: 0, page, rows, sord, sidx, ...screenForm })
    .then((res) => {
      isLoaded.value = true;
      if (res.code == 0) {
        tableData.value = res.data.rows;
        pageProps.records = res.data.records;
      } else {
        $message.error(res.err);
      }
    });
};
const fetchTaskType = () => {
  dropdownService.selectDevOpsType().then((res) => {
    if (res.code == 0) {
      taskTypes.value = res.data;
    } else {
      $message.error(res.err);
    }
  });
};
// 获取已选人员列表
const fetchMembers = () => {
  return new Promise((resolve) => {
    deviceTaskService
      .getPlanUserList({ planId: currentRow.data.id })
      .then((res) => {
        if (res.code == 0) {
          resolve(res.data);
        } else {
          resolve([]);
          $message.error(res.err);
        }
      });
  });
};
const fetchTeams = () => {
  return new Promise((resolve) => {
    deviceTaskService
      .getPlanWorkGroupList({ planId: currentRow.data.id })
      .then((res) => {
        if (res.code == 0) {
          resolve(res.data);
        } else {
          resolve([]);
          $message.error(res.err);
        }
      });
  });
};
// 监听站点变化
const districtChange = (obj) => {
  screenForm.scenes = [];
  screenForm.wageId = null;
  gridCascaderValue.value = null;
  if (obj) {
    fetchTree();
    fetchWageTypes();
  } else {
    treeData.value = [];
    wageTypes.value = [];
  }
};
// 根据站点获取时薪类型
const fetchWageTypes = () => {
  dropdownService.getDistrictWage({ districtId: screenForm.districtId }).then(res => {
    if (res.code == 0) {
      wageTypes.value = res.data
    } else {
      $message.error(res.err)
    }
  })
}
// 左侧树结构数据
const fetchTree = () => {
  const { districtId } = screenForm;
  return new Promise(() => {
    dropdownService.gridSceneTree({ districtId }).then(async (res) => {
      if (res.code == 0) {
        treeData.value = res.data.childNode;
      } else {
        $message.error(res.err);
      }
    });
  });
};
const saveTaskStateSet = () => {
  $messageBox.confirm("您确定要进行提交吗？", "提示").then((res) => {
    if (res) {
      const { districtId, id } = currentRow.data;
      planTaskService
        .setPlanStatus({ districtId, id, status: taskStateSet.value })
        .then((res) => {
          if (res.code == 0) {
            $message.success("操作成功");
            fetchData();
            showTaskStateSet.value = false;
          } else {
            $message.error(res.err);
          }
        });
    }
  });
};
const {
  $route,
  $router,
  $store,
  $common,
  $message,
  $messageBox,
  screenForm,
  screenFormRef,
  selectItems,
  tableData,
  tableHeader,
  currentRow,
  currentButton,
  tableButtons,
  rowButtons,
  pageProps,
  buttonsClickFun,
  pageChange,
  sortChange,
  restSearch,
  clearScreen,
} = templateHooks(fetchData);
// 函数定义 end
onMounted(() => {
  buttonsClickFun.data = {
    add: () => {
      currentRow.data.FormType = "add";
      showAddForm.value = true;
    },
    export: () => { },
    edit: () => {
      currentRow.data.FormType = "edit";
      showAddForm.value = true;
    },
    taskStateSet: () => {
      // 新增需求 结束状态下不可编辑任务状态
      if (currentRow.data.status == 2) {
        $message.error('此状态下不可编辑')
        return
      }
      showTaskStateSet.value = true;
      taskStateSet.value = currentRow.data.status;

    },
    copyTask: () => {
      currentRow.data.FormType = "copyTask";
      currentRow.data.id = null;
      console.log("123------------");
      showAddForm.value = true;
    },
    delete: () => {
      $messageBox
        .confirm("此操作将永久删除该数据，是否继续？", "提示")
        .then((res) => {
          if (res) {
            console.log(123);
            const { id } = currentRow.data;
            deviceTaskService.removePlan({ id }).then((res) => {
              if (res.code == 0) {
                $message.success("操作成功");
                fetchData();
              } else {
                $message.error(res.err);
              }
            });
          }
        });
    },
    prioritySet: () => {
      // 优先级设置
      showPrioritySet.value = true;
    },
  };
  nextTick(() => {
    districtScreenRef.value.fetchDistricts().then((res) => {
      if (res && res.length != 0) {
        screenForm.districtId = res[0].id;
        // fetchGridTree()
        // fetchMatter()
        fetchTree();
        fetchWageTypes()
      }
      fetchData();
      fetchTaskType();
    });
  });
});
watch(tableButtons, (val) => {
  if ($route.name == "PlanTask") {
    if (val && val.length != 0) {
      nextTick(() => {
        windowHeight.value = document.body.clientHeight;
        tableHeight.value =
          windowHeight.value -
          topScreenRef.value.clientHeight -
          170;
      });
    }
  }
});
// 生命周期 end
</script>
<script>
export default {
  name: "PlanTask",
};
</script>
