<template>
  <div class="add-plan-task-form">
    <el-steps :active="step" align-center>
      <el-step title="进行中" description="任务设置" />
      <el-step title="待进行" description="自动化设置" />
      <el-step title="待进行" description="人效管理设置" />
    </el-steps>
    <div class="main-form">
      <el-form :model="currentRow.data" ref="form" :rules="rules" label-width="120px" :inline="false" size="small"
        center>
        <plan-task-form-step1 v-model:currentRow="currentRow" :currentButton="currentButton" v-model:step="step"
          @save="save" @close="$emits('update:showAddForm', false)" v-if="step == 0"></plan-task-form-step1>
        <plan-task-form-step2 v-model:currentRow="currentRow" :currentButton="currentButton" v-model:step="step"
          @save="save" v-else-if="step == 1"></plan-task-form-step2>
        <plan-task-form-step3 v-model:currentRow="currentRow" :currentButton="currentButton" v-model:step="step"
          @save="save" v-else-if="step == 2"></plan-task-form-step3>
      </el-form>
    </div>
  </div>
</template>
<script>
export default {
  name: "addPlanTaskForm",
};
</script>
<script setup>
import { onMounted, ref, onBeforeUnmount } from "vue";
import templateHooks from "@/Hooks/templateHooks.js";
import { planTaskService } from "@/ApiService/taskCenterService";
import planTaskFormStep1 from "./planTaskFormStep1Com.vue";
import planTaskFormStep2 from "./planTaskFormStep2Com.vue";
import planTaskFormStep3 from "./planTaskFormStep3Com.vue";
const { windowHeight, $message, $messageBox } = templateHooks();
const props = defineProps({
  currentRow: Object,
  showAddForm: Boolean,
  currentButton: Object,
});
const $emits = defineEmits(["update:showAddForm", "OK"]);
const step = ref(0);
const sences = ref();
// 自定义计划开始日期验证方法
const startTimeValidatePass = (rule, value, callback) => {
  console.log("startTime", value);
  if (!value && props.currentRow.data.startStatus == 1) {
    callback(new Error("请选择计划开始时间"));
  } else {
    if (props.currentRow.data.startStatus == 1) {
      const checkeDateTime = new Date(value).getTime();
      const nowDateTime = new Date().getTime();
      const endDateTime = new Date(props.currentRow.data.endTime).getTime();
      if (checkeDateTime < nowDateTime) {
        callback(new Error("自定义计划开始日期不能小于当前日期"));
      } else if (checkeDateTime > endDateTime && endDateTime) {
        callback(new Error("自定义计划开始日期不能大于自定义计划结束日期"));
      } else {
        callback();
      }
    } else {
      callback();
    }
  }
};
// 自定义计划结束日期验证方法
const endTimeValidatePass = (rule, value, callback) => {
  console.log("endTime", value);
  if (!value && props.currentRow.data.planEndDateType == 1) {
    callback(new Error("请选择计划结束时间"));
  } else {
    if (props.currentRow.data.planEndDateType == 1) {
      const checkeDateTime = new Date(value).getTime();
      const nowDateTime = new Date().getTime();
      const startDateTime = new Date(props.currentRow.data.startTime).getTime();
      if (checkeDateTime < nowDateTime) {
        callback(new Error("自定义计划结束日期不能小于当前日期"));
      } else if (checkeDateTime <= startDateTime) {
        callback(new Error("自定义计划结束日期不能小于于自定义计划开始日期"));
      } else {
        callback();
      }
    } else {
      callback();
    }
  }
};

const rules = ref({
  districtId: [
    { required: true, message: "请选择所属站点", trigger: "change" },
  ],
  taskName: [{ required: true, message: "请输入任务名称", trigger: "blur" }],
  scenesArr: [{ required: true, message: "请选择任务场景", trigger: "change" }],
  taskCreateType: [
    { required: true, message: "请选择任务生成类型", trigger: "change" },
  ],
  actionCount: [
    { required: true, message: "请输入生成任务的人流量", trigger: "change" },
  ],
  expireTiming: [
    { required: true, message: "请输入任务过期天数", trigger: "change" },
  ],
  timeArr: [{ required: true, message: "请选择自定义时段", trigger: "change" }],
  workingTimingHour: [
    { required: true, message: "请输入标准工时小时数", trigger: "change" },
  ],
  workingTimingMinute: [
    { required: true, message: "请输入标准工时分钟数", trigger: "change" },
  ],
  transitionTimingHour: [
    { required: true, message: "请输入转场时间小时数", trigger: "change" },
  ],
  transitionTimingMinute: [
    { required: true, message: "请输入转场时间分钟数", trigger: "change" },
  ],
  readyTimingHour: [
    { required: true, message: "请输入准备时间小时数", trigger: "change" },
  ],
  readyTimingMinute: [
    { required: true, message: "请输入准备时间分钟数", trigger: "change" },
  ],
  circleNo1: [{ required: true, message: "请选择重复周期", trigger: "blur" }],
  circleNo2: [{ required: true, message: "请输入重复周期", trigger: "change" }],
  startTime: [
    {
      required: true,
      trigger: "change",
      validator: startTimeValidatePass,
    },
  ],
  endTime: [
    {
      required: true,
      trigger: "change",
      validator: endTimeValidatePass,
    },
  ],
});
const districtScreenRef = ref();
const form = ref();
// 数据定义 end

const save = (stepObj) => {
  form.value.validate((val) => {
    if (val) {
      if (stepObj == 3) {
        $messageBox
          .confirm("您确定要进行提交吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
          .then((res) => {
            if (res) {
              console.log(props.currentRow.data);
              let {
                id,
                // step1
                districtId, //站点id
                scenes, //场景集合
                taskName, //任务名称
                objectIds, //对象集合
                operationIds, //作业集合
                taskStandard, //任务标准
                taskContent, //任务方法
                taskRequire,//任务要求
                startStatus, //计划启用期限类型 默认0
                startTime, //计划启用期限
                endTime, //计划启用截止期限 不选传null
                circleStatus, //重复方式 默认不重复
                // 当circleStatus为1或2 时，
                circleType, //重复周期
                circleNo1, //周期编号 1-7
                circleNo2, //周期编号 1-30 30取月末
                eliminateType, //跳过日期类型
                userType, //选择任务执行人员类型,
                workMemberType, //选择的类型 人/班组
                workMember, //选择任务执行人员 需转化为userIds
                userStatus, //是否合作
                // step1 end
                // step2
                taskCreateType, //任务生成类型 默认值1 按人流量
                actionCount, //生成任务的人流量
                actionTimeType, //当任务生成类型为0 定时生成时使用。要求执行时段类型
                timeArr, //要求执行时段类型 自定义时间段数据 需转化为actionStartTime actionEndTime
                expireTiming, //任务过期天数
                status, //计划状态
                packageStatus, //是否为打包任务
                isCross, //是否需要跨域派单
                mustLabelIds, //是标签集合id
                notLabelIds, //否标签集合id
                // step2 end
                // step3
                workingTimingHour, //标准工时 小时
                workingTimingMinute, //标准工时 分钟
                transitionTimingHour, //转场时间 小时
                transitionTimingMinute, //转场时间 分钟
                readyTimingHour, //准备时间 小时
                readyTimingMinute, //准备时间 分钟
                redundanceTimingHour,
                redundanceTimingMinute,
                wageId
                // step3 end
              } = props.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 actionStartTime = "";
              let actionEndTime = "";
              if (taskCreateType == 0 && actionTimeType == 1) {
                actionStartTime = timeArr[0];
                actionEndTime = timeArr[1];
              }
              const workingTiming =
                workingTimingHour * 60 + workingTimingMinute;
              const transitionTiming =
                transitionTimingHour * 60 + transitionTimingMinute;
              const readyTiming = readyTimingHour * 60 + readyTimingMinute;
              const redundanceTiming =
                redundanceTimingHour * 60 + redundanceTimingMinute;
              let circleNo = null;
              if (circleStatus == 1) {
                circleNo = circleNo1;
              } else if (circleStatus == 2) {
                circleNo = circleNo2;
              }

              if (circleNo instanceof Array) {
                circleNo = circleNo.join(",");
              }
              // 数据转化 end
              planTaskService
                .addOrUpdateRoutinePlan({
                  id,
                  type: 0,
                  districtId, //站点id
                  scenes, //场景集合
                  taskName, //任务名称
                  objectIds, //对象集合
                  operationIds, //作业集合
                  taskStandard, //任务标准
                  taskContent, //任务方法
                  taskRequire,
                  startStatus, //计划启用期限类型 默认0
                  startTime, //计划启用期限
                  endTime, //计划启用截止期限 不选传null
                  circleStatus, //重复方式 默认不重复
                  userStatus,
                  mustLabelIds, //是标签集合id
                  notLabelIds, //否标签集合id
                  // 当circleStatus为1或2 时，
                  circleType, //重复周期
                  circleNo, //周期编号 1-7 1-30 30取月末
                  eliminateType, //跳过日期类型
                  userType, //选择任务执行人员类型,
                  userIds,
                  workGroupIds,
                  taskCreateType, //任务生成类型 默认值1 按人流量
                  actionCount, //生成任务的人流量
                  actionTimeType,
                  actionStartTime,
                  actionEndTime,
                  expireTiming, //任务过期天数
                  status, //计划状态
                  packageStatus, //是否为打包任务
                  isCross, //是否需要跨域派单
                  workingTiming,
                  transitionTiming,
                  readyTiming,
                  redundanceTiming,
                  wageId
                })
                .then((res) => {
                  if (res.code == 0) {
                    $message.success("操作成功");
                    $emits("update:showAddForm", false);
                    $emits("OK");
                  } else {
                    $message.error(res.err);
                  }
                });
            }
          });
        return;
      }
      step.value = stepObj;
    } else {
      return false;
    }
  });
};
const districtChange = () => { };
const cancel = () => {
  $emits("update:showAddForm", false);
};
const validate = () => {
  return form.value;
};
defineExpose({ validate });
onBeforeUnmount(() => {
  console.log('卸载组件form ');
})
</script>
<style lang="scss" scoped>
.add-plan-task-form {
  position: relative;

  .tip {
    text-align: right;
    padding: 15px 0;
  }

  .main-form {
    :deep(.el-form-item) {
      // width: 500px;
    }
  }
}
</style>
