<template>
  <div class="user-manage">
    <el-skeleton :rows="10" v-if="!isLoaded" :throttle="500" />
    <div class="main-container" v-show="isLoaded">
      <qu-search-area ref="topScreenRef" :model="screenForm" @search="restSearch" @reset="clearScreen(screenFormRef, ['districtId'])">
          <el-form-item label="所属站点" prop="districtId">
            <div class="screen-item">
              <district-screen v-model:districtId="screenForm.districtId" ref="districtScreenRef"></district-screen>
            </div>
          </el-form-item>
          <el-form-item label="任务名称">
            <div class="screen-item">
              <el-select v-model="screenForm.taskTypeId" clearable>
                <template v-for="(item, index) in operateAssignmentTypes" :key="index">
                  <el-option :label="item.name" :value="item.id"></el-option>
                </template>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="设置类型" label-width="80px">
            <div class="screen-item">
              <el-select v-model="screenForm.packageStatus" placeholder="" clearable filterable>
                <el-option :label="item.value" :value="item.key" v-for="item in selectItems['packageStatus']"
                  :key="item.key">
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="是否跨域派单">
            <div class="screen-item">
              <el-select v-model="screenForm.isCross" placeholder="" clearable filterable>
                <el-option :label="item.value" :value="item.key" v-for="item in selectItems['isCross']" :key="item.key">
                </el-option>
              </el-select>
            </div>
          </el-form-item>
      </qu-search-area>
      <div class="main-table">
        <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="showSet">
        <el-dialog v-model="showSet" :title="
          currentRow.data.packageStatus === 0 ? '按站点设置' : '按场景设置'
        ">
          <el-form :model="currentRow.data" ref="editFormRef" label-width="150px" :rules="editFormRules">
            <el-form-item label="站点名称" prop="districtId">
              <div class="form-item">
                <district-screen v-model:districtId="currentRow.data.districtId" ref="editDistrictRef"
                  @districtChange="districtChange" :disabled="!!currentRow.data.id"></district-screen>
              </div>
            </el-form-item>
            <template v-if="currentRow.data.packageStatus == 1">
              <el-form-item label="场景名称" prop="scenesArr" v-if="!currentRow.data.id">
                <el-cascader v-model="currentRow.data.scenesArr" placeholder="请选择场景" :options="options"
                  :props="scenesProps" clearable filterable collapse-tags collapse-tags-tooltip ref="sceneRef"
                  :show-all-levels="false">
                </el-cascader>
              </el-form-item>
              <el-form-item label="场景名称" v-else>
                <span>{{ currentRow.data.sceneString }}</span>
              </el-form-item>
            </template>
            <el-form-item label="任务名称" prop="taskTypeIds" v-if="!currentRow.data.id">
              <el-select v-model="currentRow.data.taskTypeIds" placeholder="请选择任务名称" clearable filterable multiple>
                <el-option :label="item.name" :value="item.id" v-for="item in operateAssignmentTypes" :key="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="任务名称" v-else>
              <span>{{ currentRow.data.taskName }}</span>
            </el-form-item>
            <el-form-item label="禁用时间" prop="actionEndTime">
              <div class="form-item">
                <el-time-picker arrow-control v-model="currentRow.data.actionEndTime" placeholder="禁用时间"
                  value-format="HH:mm:ss">
                </el-time-picker>
              </div>
            </el-form-item>
            <el-form-item label="启用时间" prop="actionStartTime">
              <div class="form-item">
                <el-time-picker arrow-control v-model="currentRow.data.actionStartTime" placeholder="启用时间"
                  value-format="HH:mm:ss">
                </el-time-picker>
              </div>
            </el-form-item>
            <el-form-item label="超时时间（分）" prop="workingTiming">
              <div class="form-item">
                <el-input-number v-model="currentRow.data.workingTiming" :min="1" :controls="false">
                </el-input-number>
              </div>
            </el-form-item>
            <el-form-item label="任务执行人员">
              <el-select v-model="currentRow.data.userType" value-key="" placeholder="" filterable
                :disabled="!currentRow.data.districtId" currentRow.data.workMember=[]>
                <el-option v-for="item in choosePeopleType" :key="item.key" :label="item.value" :value="item.key">
                </el-option>
              </el-select>
              <el-button type="primary" :disabled="!currentRow.data.userType" @click="showChoosePeople = true">选择任务执行人员
              </el-button>
            </el-form-item>
            <el-form-item label="" prop="workMember" v-if="
              currentRow.data.userType == 1
            ">
              <template v-for="item in currentRow.data.workMember" :key="item.id">
                <el-tag type="danger" size="small" effect="dark" style="margin-right: 5px">
                  {{ item.name }}
                </el-tag>
              </template>
            </el-form-item>
            <el-form-item label="" prop="workMember" v-else-if="
              currentRow.data.userType == 2
            ">
              <template v-for="item in currentRow.data.workMember" :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="是否跨域派单">
              <el-select v-model="currentRow.data.isCross" placeholder="" clearable filterable>
                <el-option :label="item.value" :value="item.key" v-for="item in selectItems['isCross']" :key="item.key">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="时薪类型">
              <el-select v-model="currentRow.data.wageId" placeholder="" clearable filterable @change="wageTypeChange">
                <el-option :label="item.name" :value="item.id" v-for="item in wageTypes" :key="item.id">
                </el-option>

              </el-select>
            </el-form-item>
            <el-form-item label="设定工时" prop="wageHour" v-if="currentRow.data.wageId != null && currentRow.data.wageId">
              <div class="form-item">
                <el-input-number v-model="currentRow.data.wageHour" step-strictly :min="0" :step="0.01"
                  :controls="false" :precision="2" placeholder="请输入工时">
                </el-input-number>

              </div>
            </el-form-item>
            <el-form-item label="是否任务打卡">
              <el-select v-model="currentRow.data.clockFlag" placeholder="" clearable filterable>
                <el-option :label="item.value" :value="item.key" v-for="item in selectItems['clockFlag']" :key="item.key">
                </el-option>

              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="showSet = false">取消</el-button>
              <el-button type="primary" @click="save">确定</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
      <div v-if="showChoosePeople">
        <el-dialog title="选择任务执行人员" v-model="showChoosePeople" fullscreen>
          <div>
            <!-- <choose-task-people
              v-model:showChoosePeople="showChoosePeople"
              :currentRow="currentRow"
              :defaultProps="defaultProps"
              @OK="getSelectWorkMember"
            ></choose-task-people> -->
            <plan-executor-form v-model:showChoosePeople="showChoosePeople" :currentRow="currentRow"
              :defaultProps="defaultProps" @OK="getSelectWorkMember"></plan-executor-form>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
  <!-- 任务配置弹窗 start-->
  <div v-if="showTaskConfig">
    <el-dialog title="任务配置" width="500px" v-model="showTaskConfig">
      <el-form
        :model="taskConfigForm"
        ref="taskConfigFormRef"
        label-width="120px"
      >
        <el-form-item label="是否生成任务">
          <el-select  style="width: 320px" v-model="taskConfigForm.taskFlag" placeholder=""  filterable>
            <el-option :label="item.value" :value="item.key" v-for="item in [{key: 0,value: '关闭'},{key: 1,value: '开启'}]" :key="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否通知">
          <el-select  style="width: 320px" v-model="taskConfigForm.noticeFlag" placeholder=""  filterable>
            <el-option :label="item.value" :value="item.key" v-for="item in [{key: 0,value: '关闭'},{key: 1,value: '开启'}]" :key="item.key">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            style="width: 90px"
            @click="showTaskConfig = false"
            >取消</el-button
          >
          <el-button style="width: 90px" type="primary" @click="submitTaskConfigForm"
            >提交</el-button
          >
        </span>
      </template>
    </el-dialog>
  </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, watch, nextTick, computed } from "vue";
import templateHooks from "@/Hooks/templateHooks";
import { deviceTaskService,setPlanTaskOrderService } from "@/ApiService/taskCenterService";
import { dropdownService } from "@/ApiService/dropdownService";
import chooseTaskPeople from "@/Components/taskCenter/taskSet/chooseTaskPeopleCom.vue";
import planExecutorForm from "@/Components/taskCenter/taskSet/planExecutorFormCom.vue";
import prioritySetCom from "@/Components/taskCenter/taskSet/prioritySetCom.vue";
const isLoaded = ref(false);
const tableLoading = ref(false);
const topScreenRef = ref();
const districtScreenRef = ref();
const editDistrictRef = ref();
const windowHeight = ref(0);
const operateAssignmentTypes = ref([]);
const showSet = ref(false);
const tableHeight = ref(500);

const editFormRules = ref({
  districtId: [
    { required: true, message: "请选择站点名称", trigger: "change" },
  ],
  scenesArr: [{ required: true, message: "请选择场景名称", trigger: "change" }],
  taskTypeIds: [
    { required: true, message: "请选择任务名称", trigger: "change" },
  ],
  workingTiming: [
    { required: true, message: "请输入超时时间", trigger: "change" },
  ],
  wageHour: [
    { required: true, message: "输入设定工时", trigger: "change" },
  ]
});

const choosePeopleType = [
  {
    key: 0,
    value: "不限人员",
  },
  {
    key: 1,
    value: "选择任务执行人员",
  },
  {
    key: 2,
    value: "选择任务执行班组",
  },
];
const showChoosePeople = ref(false);
const defaultProps = computed(() => {
  return {
    buttonId: currentButton.data.buttonId,
    planId: currentRow.data.id,
  };
});
const editFormRef = ref();
const options = ref([]);
const scenesProps = {
  expandTrigger: "hover",
  checkStrictly: true,
  children: "childNode",
  label: "name",
  value: "gridId",
  multiple: true,
  disabled: "disable",
};
const sceneRef = ref();
const wageTypes = ref([])
const showPrioritySet = ref(false); // 优先级设置弹窗
const showTaskConfig = ref(false); // 任务配置弹窗
const taskConfigFormRef = ref();
// 任务配置表单
const taskConfigForm = reactive({}) 
// 数据定义 end
// 任务配置
const submitTaskConfigForm = () => {
  taskConfigForm.planId = currentRow.data.id;
  $messageBox.confirm("您确定要进行提交吗？", "提示",{
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
  .then(() => {
    console.log(deviceTaskService.setPlanFlag);
    deviceTaskService.setPlanFlag(taskConfigForm).then((res) => {
      console.log(res);
      if (res.code == 0){
        $message.success(res.data);
        showTaskConfig.value = false;
        fetchData();
      }else {
        $message.error(res.err);
      }
    })
  })
}
// 优先级设置
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 wageTypeChange = (e) => {
  console.log(e);
  currentRow.data.wageHour = null
}
// 获取暂存的选中人员
const getSelectWorkMember = ({ workMember, type }) => {
  console.log("主页面获取暂存的选中人员");
  currentRow.data.workMember = workMember;
  currentRow.data.userType = type;
};
// 获取已选人员列表
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 fetchAssignmentType = () => {
  dropdownService.selectDevOpsType().then((res) => {
    if (res.code == 0) {
      operateAssignmentTypes.value = res.data;
    } else {
      $message.error(res.err);
    }
  });
};
const districtChange = (obj) => {
  currentRow.data.workMember = [];
  currentRow.data.wageId = null;
  if (obj) {
    fetchSceneTree();
    fetchWageType()
  } else {
    options.value = [];
    wageTypes.value = []
  }
};
const fetchWageType = () => {
  const { districtId } = currentRow.data
  dropdownService.getDistrictWage({ districtId }).then((result) => {
    if (result.code == 0) {
      wageTypes.value = result.data
    } else {
      $message.error(result.err)
    }
  }).catch((err) => {

  });
}
const fetchSceneTree = () => {
  dropdownService
    .gridSceneTree({ districtId: currentRow.data.districtId })
    .then((res) => {
      if (res.code == 0) {
        options.value = res.data.childNode;
      } else {
        $message.error(res.err);
      }
    });
};
const buttonClick = (button) => {
  currentButton.data = button;
  const fileterArr = ["packageStatus", "workingTiming"];
  for (let i in currentRow.data) {
    if (i != "packageStatus") {
      currentRow.data[i] = null;
    }
  }
  currentRow.data.workingTiming = 40;
  currentRow.data.taskTypeIds = [];
  currentRow.data.workMember = [];
  currentRow.data.userType = 0;
  currentRow.data.isCross = 0;
  currentRow.data.clockFlag = 0;
  buttonsClickFun.data[button.enName]();
};
const rowButtonClick = ({ row, $column }) => {
  for (let i in row) {
    currentRow.data[i] = row[i];
  }
  currentButton.data = $column;
  buttonsClickFun.data[$column.enName]();
};
const fetchData = () => {
  //   setTimeout(() => {
  //     isLoaded.value = true;
  //   }, 1500);
  const { page, rows, sord, sidx } = pageProps;
  tableLoading.value = false;
  deviceTaskService
    .planDevOpsPageList({
      page,
      rows,
      sord,
      sidx,
      ...screenForm,
    })
    .then(
      (res) => {
        if (res.code == 0) {
          tableData.value = res.data.rows;
          pageProps.records = res.data.records;
        } else {
          $message.error(res.err);
        }
        isLoaded.value = true;
        tableLoading.value = false;
      },
      () => {
        isLoaded.value = true;
        tableLoading.value = false;
      }
    );
};
const save = () => {
  editFormRef.value.validate((val) => {
    if (!val) {
      return false;
    }
    let tipText = "";
    if (currentRow.data.actionEndTime) {
      if (!currentRow.data.actionStartTime) {
        tipText = "启用时间不能为空";
      }
    }
    if (currentRow.data.actionStartTime) {
      if (!currentRow.data.actionEndTime) {
        tipText = "禁用时间不能为空";
      }
    }
    if (tipText) {
      $message.error(tipText);
      return;
    }
    $messageBox
      .confirm("您确定要进行提交吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
      .then(() => {
        const {
          actionEndTime,
          actionStartTime,
          districtId,
          packageStatus,
          taskTypeIds,
          workingTiming,
          workMember,
          id,
          userType,
          isCross,
          wageId,
          wageHour,
          clockFlag,
        } = currentRow.data;
        let userIds = [];
        let workGroupIds = [];
        if (userType == 1) {
          userIds = Array.from(workMember, ({ userId }) => userId); //执行人员
        } else if (userType == 2) {
          workGroupIds = Array.from(
            workMember,
            ({ workGroupId }) => workGroupId
          );
        }
        let postData = {};
        let scenes = [];
        if (id) {
          postData = {
            districtId,
            actionEndTime,
            actionStartTime,
            workingTiming,
            userIds,
            type: 1,
            id,
            userType,
            workGroupIds,
            isCross,
            wageId,
            wageHour,
            clockFlag
          };
          edit(postData);
          return;
        }
        if (currentRow.data.packageStatus == 1) {
          scenes = sceneRef.value.getCheckedNodes().map((item) => {
            const { sceneId: id, name, level } = item.data;
            return {
              id,
              name,
              level,
            };
          });
        }

        postData = {
          actionEndTime,
          actionStartTime,
          districtId,
          scenes,
          packageStatus,
          taskTypeIds,
          workingTiming,
          userIds,
          type: 1,
          userType,
          workGroupIds,
          isCross,
          wageId,
          wageHour,
          clockFlag
        };

        deviceTaskService.addDevOpsPlan(postData).then((res) => {
          if (res.code == 0) {
            $message.success("操作成功");
            showSet.value = false;
            fetchData();
          } else {
            $message.error(res.err);
          }
        });
      });
  });
};
const edit = (postData) => {
  deviceTaskService.updateDevOpsPlan(postData).then((res) => {
    if (res.code == 0) {
      $message.success("操作成功");
      showSet.value = false;
      fetchData();
    } else {
      $message.error(res.err);
    }
  });
};
// const { pageChange, sortChange, restSearch, clearScreen } =
//   templateHooks(fetchData);
const {
  $route,
  $router,
  $store,
  $message,
  $messageBox,
  screenForm,
  screenFormRef,
  selectItems,
  tableData,
  tableHeader,
  currentRow,
  currentButton,
  tableButtons,
  rowButtons,
  pageProps,
  buttonsClickFun,
  pageChange,
  sortChange,
  restSearch,
  clearScreen,
} = templateHooks(fetchData);
currentRow.data = {
  taskTypeIds: [],
  userType: 0,
  workMember: []
};
// 函数定义 end
onMounted(() => {
  // 获取任务名称列表
  fetchAssignmentType();
  buttonsClickFun.data = {
    districtSet: () => {
      showSet.value = true;
      currentRow.data.packageStatus = 0;
      currentRow.data.workingTiming = 40;
      nextTick(() => {
        editDistrictRef.value.fetchDistricts();

      });
    },
    sceneSet: () => {
      showSet.value = true;
      currentRow.data.packageStatus = 1;
      currentRow.data.workingTiming = 40;
      nextTick(() => {
        editDistrictRef.value.fetchDistricts();

      });
    },
    edit: () => {
      // 判断任务类型 选择弹窗类型
      //
      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;

        });
      }
      // 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;
      //       }
      //     });
      //   }
      // });
      showSet.value = true;
      nextTick(() => {
        editDistrictRef.value.fetchDistricts();
        fetchWageType()
      });
    },
    delete: () => {
      $messageBox
        .confirm("此操作将永久删除该数据，是否继续？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then((rsp) => {
          if (rsp) {
            deviceTaskService
              .removePlan({ id: currentRow.data.id })
              .then((res) => {
                if (res.code == 0) {
                  $message.success("操作成功");
                  fetchData();
                } else {
                  $message.error(res.er);
                }
              });
          }
        });
    },
    export: () => {
      deviceTaskService.planDevopsExport(screenForm);
    },
    prioritySet: () => {
      // 优先级设置
      showPrioritySet.value = true;
    },
    // 任务配置
    taskConfig:()=>{
      taskConfigForm.taskFlag = currentRow.data.taskFlag;
      taskConfigForm.noticeFlag = currentRow.data.noticeFlag;
      showTaskConfig.value = true;
    }
  };
  nextTick(() => {
    districtScreenRef.value.fetchDistricts().then((res) => {
      if (res && res.length != 0) {
        screenForm.districtId = res[0].id;
      }
      fetchData();
    });
  });
});
watch(showSet, val => {
  if (!val) {
    wageTypes.value = []
  }
})
watch(tableButtons, (val) => {
  if ($route.name == "DeviceTask") {
    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: "DeviceTask",
};
</script>
