<template>
  <div class="p-2">
    <PageHeader></PageHeader>
    <div class="EditBody">
      <div class="title">
        <div>基本信息</div>
      </div>
      <div class="bodyBox">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" label-position="right">
          <el-form-item label="任务名称" prop="taskName">
            <el-input maxlength="20" v-model="form.taskName" placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="巡检人员" prop="inspectorId">
            <div class="inspectorIdsBox">
              <div v-for="(item, index) in checkoutUserlist" :key="index" class="inspector_items">
                <div class="name">{{ item.nickName }}</div>
                <i @click="handleDelete(item.userId)" class="deleteAction">
                  <el-icon><Delete /></el-icon>
                </i>
              </div>
              <RepairUser
                titleName="巡检人员"
                @change="handleUserChange"
                returnvalue="*"
                :is-multiple="true"
                user-type="inspection"
                ref="RepairUserRef"
              >
                <template #default>
                  <div @click="handleAddUser" class="inspector_items add flex flex-items-center justify-center">
                    <el-icon><Plus /></el-icon>
                    <span class="ml-10px"> 添加 </span>
                  </div>
                </template>
              </RepairUser>
            </div>
          </el-form-item>
          <el-form-item label="巡更日期" prop="taskTime">
            <el-date-picker
              range-separator="到"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              v-model="taskTime"
              @update:model-value="
                (val) => {
                  if (val.length > 0) {
                    form.taskTime = val.join(' - ');
                  }
                }
              "
              type="daterange"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="提醒时间" prop="remindTime">
            <el-select v-model="form.remindTime" placeholder="请选择" style="width: 100%">
              <el-option v-for="item in com_inspection_remind_tiime" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="关联计划" prop="planId">
            <el-select @change="handleChangeMap" v-model="form.planId" placeholder="请选择" style="width: 100%">
              <el-option v-for="item in planList"  :disabled="item.status === '1'" :key="item.id" :label="item.planName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="计划路线" prop="planId">
            <MapWrapper v-loading="mapLoading" :disabled="true" ref="MapWrapperRef"></MapWrapper>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submit">提交</el-button>
            <el-button @click="outback">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import RepairUser from '@/components/Holder/repairUser.vue';
import PageHeader from '@/components/Pageheader/index.vue';
import { Delete, Plus } from '@element-plus/icons-vue';
import { ref } from 'vue';
import { listPlan } from '@/api/system/InspectionPlan';
import { addTask, getTask, updateTask } from '@/api/system/InspectionTask';
import { getRoute } from '@/api/system/InspectionRoute';
import MapWrapper from '@/components/Map/index.vue';
import { LngLat } from '@/components/Map/type';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { com_inspection_remind_tiime } = toRefs<any>(proxy?.useDict('com_inspection_remind_tiime'));
const route = useRoute();
const router = useRouter();

const form = ref({
  id: null,
  taskName: '', // 巡检计划名称
  inspectorId: '', // 巡检人员
  taskTime: '', // 执行日期
  remindTime: '', // 提醒时间
  planId: '' // 计划路线id
});
const taskTime = ref([]);
const rules = ref({
  taskName: [{ required: true, message: '请输入巡检任务名称', trigger: 'blur' }],
  taskTime: [{ required: true, message: '请选择巡检任务时间', trigger: 'blur' }],
  remindTime: [{ required: true, message: '请选择巡检任务提醒时间', trigger: 'blur' }],
  inspectorId: [{ required: true, message: '请选择巡检人员', trigger: 'blur' }],
  planId: [{ required: true, message: '请选择巡检计划', trigger: 'blur' }]
});
// 巡检计划id
const editId = ref(null);

// 初始化
// 路线列表
const planList = ref([]);
async function init() {
  // 获取  路线 列表
  const res = await listPlan();
  planList.value = res.rows;
  if (route.query.id) {
    editId.value = route.query.id;
    getTask(editId.value).then((res) => {
      form.value = {
        id: res.data.id,
        taskName: res.data.taskName, // 巡检计划名称
        inspectorId: res.data.inspectorId, // 巡检人员
        taskTime: '', // 巡检人员
        remindTime: res.data.remindTime, // 提醒时间
        planId: res.data.planId // 计划路线id
      };
      taskTime.value = res.data.taskTime ? res.data.taskTime.split(' - ') : [];
      checkoutUserlist.value = Array.isArray(res.data.inspectorInfo) ? res.data.inspectorInfo : [res.data.inspectorInfo];
      handleChangeMap(res.data.planId);
    });
  }
}

// 选择 巡检人员
const RepairUserRef = ref<InstanceType<typeof RepairUser>>();
function handleAddUser() {
  RepairUserRef.value.open();
}
const checkoutUserlist = ref([]);
function handleUserChange(val: any[]) {
  checkoutUserlist.value = val;
}
function handleDelete(id: string) {
  checkoutUserlist.value = checkoutUserlist.value.filter((item) => item.userId !== id);
}

// 返回
function outback() {
  router.back();
}
const mapLoading = ref(false);

const MapWrapperRef = ref<InstanceType<typeof MapWrapper>>();

function handleChangeMap(val: string) {
  mapLoading.value = true;
  const find = planList.value.find((item) => item.id === val);
  if (find) {
    const route = find.routeList[find.routeList.length - 1];
    if (route) {
      getRoute(route.id)
        .then((res) => {
          if (res) {
            MapWrapperRef.value.clearMapMarker();
            if (res.data.points && res.data.points.length > 0) {
              res.data.points.forEach((item) => {
                const angular = item.location.split(',').map(Number).filter(Boolean) as LngLat;
                MapWrapperRef.value.addMarker_more(angular, item.pointName, item.id);
              });
            }
            // 巡检路线
            if (res.data.pathPoints) {
              MapWrapperRef.value.renderSavedPath(res.data.pathPoints);
            }
          }
        })
        .finally(() => {
          mapLoading.value = false;
        });
    } else {
      mapLoading.value = false;
    }
  } else {
    mapLoading.value = false;
  }
}

onMounted(() => {
  init();
});

const formRef = ref();
function submit() {
  if (taskTime.value.length > 0) {
    form.value.taskTime = taskTime.value.join(' - ');
  } else {
    form.value.taskTime = '';
  }
  form.value.inspectorId = checkoutUserlist.value.map((item) => item.userId).join(',');
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (editId.value) {
        updateTask(form.value).then(() => {
          ElMessage.success('编辑成功');
          outback();
        });
      } else {
        addTask(form.value).then(() => {
          ElMessage.success('添加成功');
          outback();
        });
      }
    }
  });
}
</script>

<style scoped lang="scss">
.EditBody {
  margin-top: 20px;
  padding: 30px;
  background-color: white;
  .bodyBox {
    width: 600px;
    margin: 20px auto 0;
  }
  .inspectorIdsBox {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    .inspector_items {
      width: 120px;
      height: 40px;
      line-height: 40px;
      margin: 5px;
      text-align: center;
      border-radius: 5px;
      background-color: #ddeaff;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 2px;
      .name {
        overflow: hidden;
        text-overflow: ellipsis;
        text-wrap: nowrap;
      }
      &.add {
        background-color: #ddeaff25;
        border: 1px dashed #ccc;
        cursor: pointer;
        &:hover {
          background-color: rgba(221, 234, 255, 0.199);
          border-color: #44a0ff;
          color: #44a0ff;
        }
      }
      .deleteAction {
        margin-left: 10px;
        cursor: pointer;
        &:hover {
          color: red;
        }
      }
    }
  }
  .week-items {
    width: 90px;
    height: 30px;
    line-height: 30px;
    border-radius: 5px;
    cursor: pointer;
    margin: 10px 5px;
    border: 1px solid #ccc;
    color: #000;
    display: flex;
    align-items: center;
    .iconBox {
      width: 30px;
      height: 30px;
      margin-left: 5px;
      text-align: center;
      line-height: 30px;
    }
    &.active {
      color: rgba(26, 117, 255, 1);
      background-color: rgba(26, 117, 255, 0.15);
      border: none;
    }
  }

  .mapbox {
    margin-top: 20px;
    width: 100%;
    height: 400px;
    border: 1px solid #ccc;
  }
}
</style>
