<template>
  <div class="step1">
    <el-divider content-position="left">在哪做？</el-divider>
    <el-form-item label="所属站点" prop="districtId">
      <district-screen
        v-model:districtId="currentRow.data.districtId"
        ref="districtScreenRef"
        @districtChange="districtChange"
        :disabled="currentRow.data.id ? true : false"
      ></district-screen>
    </el-form-item>
    <el-form-item label="任务场景" prop="scenesArr">
      <el-cascader
        v-model="currentRow.data.scenesArr"
        placeholder="请选择场景"
        :options="scenesOptions"
        :props="scenesProps"
        clearable
        filterable
        collapse-tags
        collapse-tags-tooltip
        ref="sceneRef"
        :disabled="!currentRow.data.districtId"
        :show-all-levels="false"
        @change="scenesChange('dom')"
      >
      </el-cascader>
    </el-form-item>
    <el-divider content-position="left">做什么？</el-divider>
    <el-form-item label="任务名称" prop="taskName">
      <el-input
        v-model="currentRow.data.taskName"
        placeholder=""
        clearable
        maxlength="13"
      ></el-input>
    </el-form-item>
    <el-form-item label="任务对象">
      <el-cascader
        v-model="currentRow.data.objectArr"
        placeholder="请选择对象"
        :options="objectOptions"
        :props="objectProps"
        clearable
        filterable
        collapse-tags
        collapse-tags-tooltip
        ref="objectRef"
        :show-all-levels="false"
        :disabled="!currentRow.data.scenesArr"
        @change="objectChange('dom')"
      >
      </el-cascader>
    </el-form-item>
    <el-form-item label="任务作业">
      <div>
        <template
          v-for="(item, index) in currentRow.data.selectedOperations"
          :key="index"
        >
          <el-tag
            type="danger"
            size="small"
            effect="plain"
            style="margin-right: 10px"
            >{{ item.name }}</el-tag
          >
        </template>
      </div>
      <div>
        <el-button
          type="primary"
          size="default"
          @click="showOperation = true"
          :disabled="
            !currentRow.data.districtId ||
            !currentRow.data.objectArr ||
            currentRow.data.objectArr.length == 0
          "
          >选择作业</el-button
        >
      </div>
    </el-form-item>
    <el-divider content-position="left">怎么做？</el-divider>
    <el-form-item label="任务要求">
      <el-input
        v-model="currentRow.data.taskRequire"
        placeholder="请简要描述任务要求要求（非必填，限500以内）"
        size="small"
        type="textarea"
        maxlength="500"
        show-word-limit
        clearable
      ></el-input>
    </el-form-item>
    <!-- <el-form-item label="任务完成标准">
      <el-input v-model="currentRow.data.taskStandard" placeholder="请简要描述任务完成的标准（非必填，限500以内）" size="small"
        type="textarea" maxlength="500" show-word-limit clearable></el-input>
    </el-form-item>
    <el-form-item label="任务执行方法">
      <el-input v-model="currentRow.data.taskContent" placeholder="请简要描述任务执行的方法（非必填，限500以内）" size="small"
        type="textarea" maxlength="500" show-word-limit clearable></el-input>
    </el-form-item> -->
    <el-divider content-position="left">哪天做？</el-divider>
    <el-form-item label="计划启用期限" style="margin-bottom: 40px">
      <div>
        <div>
          <el-select
            v-model="currentRow.data.startStatus"
            value-key=""
            placeholder=""
          >
            <el-option label="系统默认" :value="0"> </el-option>
            <el-option label="自定义计划开始日期" :value="1"> </el-option>
          </el-select>
          至
          <el-select
            v-model="currentRow.data.planEndDateType"
            value-key=""
            placeholder=""
          >
            <el-option label="永久有效" :value="0"> </el-option>
            <el-option label="自定义计划结束日期" :value="1"> </el-option>
          </el-select>
        </div>
        <div style="display: flex; align-items: center">
          <el-form-item label="" prop="startTime">
            <el-date-picker
              v-model="currentRow.data.startTime"
              type="datetime"
              placeholder="请选择自定义计划开始日期"
              :disabled="currentRow.data.startStatus != 1"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>

          <div style="padding: 0 10px">至</div>

          <el-form-item label="" prop="endTime">
            <el-date-picker
              v-model="currentRow.data.endTime"
              type="datetime"
              :disabled="currentRow.data.planEndDateType != 1"
              placeholder="请选择自定义计划结束日期"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </div>
      </div>
    </el-form-item>

    <el-form-item label="重复">
      <el-select
        v-model="currentRow.data.circleStatus"
        value-key=""
        placeholder=""
        clearable
        filterable
        @change="repeatTypeChange"
      >
        <el-option label="不重复" :value="0"></el-option>
        <el-option label="重复方式一" :value="1"></el-option>
        <el-option label="重复方式二" :value="2"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item v-if="currentRow.data.circleStatus == 1">
      <el-select
        v-model="currentRow.data.circleType"
        value-key=""
        placeholder=""
        clearable
        filterable
        @change="currentRow.data.circleNo1 = []"
      >
        <el-option label="每周重复" :value="1"> </el-option>
        <el-option label="每月重复" :value="2"> </el-option>
      </el-select>
      <el-form-item label="" prop="circleNo1">
        <el-select
          v-model="currentRow.data.circleNo1"
          value-key=""
          placeholder=""
          clearable
          filterable
          multiple
        >
          <el-option
            v-for="item in repeatDateArr"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form-item>

    <el-form-item v-if="currentRow.data.circleStatus == 2">
      <el-form-item label="" prop="circleNo2">
        <span>每隔</span>
        <el-input-number
          v-model="currentRow.data.circleNo2"
          :min="1"
          :step="1"
          :controls="false"
          controls-position=""
        >
        </el-input-number>
      </el-form-item>
      <el-select
        v-model="currentRow.data.circleType"
        value-key=""
        placeholder=""
        clearable
        filterable
      >
        <el-option label="天" :value="0"> </el-option>
        <el-option label="周" :value="1"> </el-option>
        <el-option label="月" :value="2"> </el-option>
      </el-select>
      <span>启用一次</span>
    </el-form-item>
    <el-form-item label="跳过日期">
      <el-select
        v-model="currentRow.data.eliminateType"
        value-key=""
        placeholder="不跳过"
        clearable
        filterable
      >
        <el-option label="不跳过" :value="0"> </el-option>
        <el-option label="跳过法定节假日" :value="1"> </el-option>
        <el-option label="跳过法定工作日" :value="2"> </el-option>
      </el-select>
    </el-form-item>
    <el-divider content-position="left">谁来做？</el-divider>
    <el-form-item label="任务执行人员">
      <el-select
        v-model="currentRow.data.userType"
        value-key=""
        placeholder=""
        :disabled="!currentRow.data.districtId"
        @change="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="showTaskExecutor = 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-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="是否合作完成" v-if="currentRow.data.userType">
      <el-select
        v-model="currentRow.data.userStatus"
        value-key=""
        placeholder="请选择是否合作完成"
      >
        <el-option label="否" :value="0"></el-option>
        <el-option
          label="是"
          :value="1"
          :disabled="
            currentRow.data.workMember.length <= 1 &&
            currentRow.data.userType == 1
          "
        >
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="save">下一步</el-button>
    </el-form-item>
    <div v-if="showTaskExecutor">
      <el-dialog title="选择任务执行人员" v-model="showTaskExecutor" fullscreen>
        <!-- <choose-task-people
          v-model:showChoosePeople="showTaskExecutor"
          :currentRow="currentRow"
          :defaultProps="defaultProps"
          @OK="getSelectWorkMember"
        ></choose-task-people> -->
        <plan-executor-form
          v-model:showChoosePeople="showTaskExecutor"
          :currentRow="currentRow"
          :defaultProps="defaultProps"
          @OK="getSelectWorkMember"
        ></plan-executor-form>
      </el-dialog>
    </div>
    <div v-if="showOperation">
      <el-dialog title="选择任务作业" v-model="showOperation" fullscreen>
        <choose-operation
          :defaultProps="operationProps"
          v-model:showOperation="showOperation"
          :selectedOperations="selectedOperations"
          :objectIds="currentRow.data.objectIds"
          @OK="getSelectOperations"
        >
        </choose-operation>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  computed,
  watch,
  nextTick,
  onBeforeUnmount,
} from "vue";
import chooseTaskPeople from "@/Components/taskCenter/taskSet/chooseTaskPeopleCom.vue";
import planExecutorForm from "@/Components/taskCenter/taskSet/planExecutorFormCom.vue";
import chooseOperation from "@/Components/taskCenter/taskSet/planTask/chooseOperationCom.vue";
import { dropdownService } from "@/ApiService/dropdownService";
import templateHooks from "@/Hooks/templateHooks.js";
const { $message } = templateHooks();
const props = defineProps({
  currentRow: Object,
  currentButton: Object,
});
const $emits = defineEmits(["save", "close"]);
const scenes = ref([]);
const districtScreenRef = ref();
const choosePeopleType = [
  {
    key: 0,
    value: "不限人员",
  },
  {
    key: 1,
    value: "选择任务执行人员",
  },
  {
    key: 2,
    value: "选择任务执行班组",
  },
];
const showTaskExecutor = ref(false);
const defaultProps = computed(() => {
  return {
    buttonId: props.currentButton.data.buttonId,
    planId: props.currentRow.data.id,
  };
});

const sceneRef = ref();
const objectRef = ref();
const options = ref([]);
const scenesOptions = ref([]);
const objectOptions = ref([]);
const scenesProps = {
  expandTrigger: "hover",
  checkStrictly: true,
  children: "childNode",
  label: "name",
  value: "sceneId",
  multiple: true,
  disabled: "disable",
};
const objectProps = {
  expandTrigger: "hover",
  checkStrictly: true,
  children: "childrenNode",
  label: "name",
  value: "id",
  multiple: true,
  disabled: "disable",
};
const operationProps = computed(() => {
  return {
    districtId: props.currentRow.data.districtId,
  };
});
const defaultDistrictId = computed(() => {
  return props.currentRow.data.districtId;
});
const defaultScenesArr = computed(() => {
  return props.currentRow.data.scenesArr;
});
const defaultObjectArr = computed(() => {
  return props.currentRow.data.objectArr;
});
const planEndDateType = computed(() => {
  return props.currentRow.data.planEndDateType;
});
const repeatDateArr = computed(() => {
  let dateArr = [];
  if (props.currentRow.data.circleType == 1) {
    dateArr = [
      { id: 1, name: "周一" },
      { id: 2, name: "周二" },
      { id: 3, name: "周三" },
      { id: 4, name: "周四" },
      { id: 5, name: "周五" },
      { id: 6, name: "周六" },
      { id: 7, name: "周日" },
    ];
  } else if (props.currentRow.data.circleType == 2) {
    for (let i = 1; i <= 32; i++) {
      if (i == 32) {
        dateArr.push({
          id: 99,
          name: "月末",
        });
      } else {
        dateArr.push({
          id: i,
          name: i,
        });
      }
    }
  }
  return dateArr;
});

const circleStatus = computed(() => {
  return props.currentRow.data.circleStatus;
});
const showOperation = ref(false);
const selectedOperations = ref([]);
// 数据定义 end
const repeatTypeChange = () => {
  props.currentRow.data.circleNo1 = [];
  props.currentRow.data.circleNo2 = null;
};
const disableEndTime = (time) => {
  if (props.currentRow.data.startTime) {
    const startTime = new Date(props.currentRow.data.startTime).getTime();
    let key = true;
    if (startTime < time.getTime()) {
      key = false;
    }
    return key;
  }
};
const disableStartTime = (time) => {
  const nowTime = new Date().getTime();

  if (time.getTime() < nowTime) {
    console.log(1233);
    return false;
  }
  if (props.currentRow.data.endTime) {
    const endTime = new Date(props.currentRow.data.endTime).getTime();
    let key = true;
    if (endTime > time.getTime()) {
      key = false;
    }
    return key;
  }
};
const close = () => {
  console.log("关闭弹窗");
  $emits("close", true);
};
// 获取暂存的选中人员
const getSelectWorkMember = ({ workMember, type }) => {
  console.log("主页面获取暂存的选中人员");
  props.currentRow.data.workMember = workMember;
  props.currentRow.data.userType = type;
  props.currentRow.data.userStatus = 0;
};
// 监听场景变化
const scenesChange = (type) => {
  console.log("--------监听场景变化----------");

  if (type) {
    const checkedNodes = sceneRef.value.getCheckedNodes();
    console.log("checkedNodes", checkedNodes);
    const sceneArr = [];
    checkedNodes.map((item) => {
      const { sceneId: id, isscene, level, name } = item.data;
      sceneArr.push({ id, isscene, level, name });
    });
    console.log(type, "scenesArr", props.currentRow.data.scenesArr);
    props.currentRow.data.scenes = sceneArr;
    objectOptions.value = []; //清空对象数据源
    props.currentRow.data.objectArr = []; //清空选择的对象数据
    props.currentRow.data.operationIds = []; //清空选择的作业数据ids
    selectedOperations.value = []; //清空选择的作业数据item
    props.currentRow.data.selectedOperations = [];
  }

  console.log("scenes:", props.currentRow.data.scenes);
  if (props.currentRow.data.scenes.length != 0) {
    fetchObjectTree();
  }
};
const objectChange = (type) => {
  console.log("--------监听对象变化----------");
  console.log("currentRowData", props.currentRow.data);
  if (type) {
    const checkedNodes = objectRef.value.getCheckedNodes();

    console.log(type, "objectCheckedNodes", checkedNodes);
    const objectArr = [];
    checkedNodes.map((item) => {
      const { id } = item.data;
      objectArr.push(id);
    });
    props.currentRow.data.objectIds = objectArr;
    props.currentRow.data.operationIds = []; //清空选择的作业数据ids
    selectedOperations.value = []; //清空选择的作业数据item
    props.currentRow.data.selectedOperations = [];
  } else {
  }

  console.log("objectIds:", props.currentRow.data.objectIds);
};
// 获取选择的作业
const getSelectOperations = (obj) => {
  selectedOperations.value = obj;
  props.currentRow.data.selectedOperations = obj;
  props.currentRow.data.operationIds = Array.from(obj, ({ id }) => id);
};
const save = () => {
  $emits("save", 1);
};
const districtChange = (obj) => {
  scenesOptions.value = [];
  objectOptions.value = [];
  props.currentRow.data.scenesArr = [];
  props.currentRow.data.objectArr = [];
  props.currentRow.data.operationIds = [];
  selectedOperations.value = [];
  props.currentRow.data.selectedOperations = [];
  props.currentRow.data.workMember = [];

  // if (obj) {
  //   fetchSceneTree();
  // }
};
const fetchSceneTree = () => {
  if (!props.currentRow.data.districtId) {
    $message.error("缺少站点id：fetchSceneTree");
    return;
  }
  dropdownService
    .gridSceneTree({ districtId: props.currentRow.data.districtId })
    .then((res) => {
      if (res.code == 0) {
        scenesOptions.value = res.data.childNode;
      } else {
        $message.error(res.err);
      }
    });
};
// 获取对象列表
const fetchObjectTree = () => {
  const { scenes, districtId } = props.currentRow.data;
  console.log(scenes, districtId);
  if (!scenes || scenes.length == 0) {
    $message.error("请选择场景");
    return;
  }
  if (!districtId) {
    $message.error("缺少站点id：fetchObjectTree");
    return;
  }
  dropdownService.getSceneObject({ scenes, districtId }).then((res) => {
    if (res.code == 0) {
      objectOptions.value = res.data.childrenNode;
      console.log("objectOptions", objectOptions.value);
    } else {
      $message.error(res.err);
    }
  });
};
// 获取作业列表
const fetchJobs = () => {};
onMounted(() => {
  districtScreenRef.value.fetchDistricts();
  selectedOperations.value = props.currentRow.data.selectedOperations;
});
const stopDefaultDistrictId = watch(
  defaultDistrictId,
  (val, old) => {
    console.log(val == old);
    if (val && val != old) {
      fetchSceneTree();
    }
  },
  {
    immediate: true,
  }
);
watch(
  defaultScenesArr,
  (val, old) => {
    if (val && val.length != 0) {
      setTimeout(() => {
        scenesChange();
      }, 1000);
    }
  },
  { immediate: true }
);
watch(
  defaultObjectArr,
  (val) => {
    // console.log(val);
    if (val && val.length != 0) {
      setTimeout(() => {
        objectChange();
      }, 1500);
    }
  },
  { immediate: true }
);
watch(planEndDateType, (val) => {
  props.currentRow.data.endTime = null;
});
watch(circleStatus, (val) => {
  console.log("circleStatus", val);
  if (val == 1) {
    props.currentRow.data.circleType = 1;
  } else if (val == 2) {
    props.currentRow.data.circleType = 0;
  }
});
onBeforeUnmount(() => {
  console.log("卸载组件form step1 ");
  stopDefaultDistrictId();
});
</script>
<script>
export default {
  name: "plan-task-form-step1",
};
</script>
