<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="计划名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入计划名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="计划状态" prop="status">
              <el-select v-model="queryParams.status" clearable placeholder="请选择计划状态">
                <el-option v-for="dict in inspection_status" :key="dict.value" :label="dict.label" :value="dict.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery"> 搜索 </el-button>
              <el-button icon="Refresh" @click="resetQuery"> 重置 </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"> 新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"> 修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"> 删除
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList" />
        </el-row>
      </template>

      <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="计划名称" align="center" show-overflow-tooltip prop="name" width="150" />
        <el-table-column label="计划编号" align="center" show-overflow-tooltip prop="id" width="150" />
        <el-table-column label="计划开始时间" align="center" show-overflow-tooltip prop="startTime" width="150" />
        <el-table-column label="计划结束时间" align="center" show-overflow-tooltip prop="endTime" width="150" />
        <el-table-column label="巡检类型" align="center" width="100">
          <template #default="scope">
            <dict-tag :options="inspection_type" :value="scope.row.inspectionType" />
          </template>
        </el-table-column>
        <el-table-column label="巡检周期(天)" align="center" show-overflow-tooltip prop="inspectionCycle" width="100" />
        <el-table-column label="巡检员" align="center" show-overflow-tooltip prop="ext1.inspectionPersonName"
          width="120" />
        <el-table-column label="备注" align="center" show-overflow-tooltip prop="remark" width="150" />
        <el-table-column label="计划状态" align="center" width="120">
          <template #default="scope">
            <dict-tag :options="inspection_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="已执行任务次数" align="center" show-overflow-tooltip prop="judgeMinValue" width="120" />
        <el-table-column label="创建时间" align="center" show-overflow-tooltip prop="createTime" width="120" />
        <el-table-column label="操作" align="center" width="140" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-if="scope.row.status == 1" size="small" link type="primary"
              @click="changeStatus(scope.row, '2')">停止</el-button>
            <template v-else>
              <el-button size="small" link type="primary" @click="changeStatus(scope.row, '1')">启动</el-button>
              <el-button size="small" link type="primary" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="small" link type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="950px" append-to-body>
      <el-form ref="addFormRef" :model="form" label-width="110px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="计划名称" prop="name" :rules="[{ required: true, message: '计划名称不能为空', trigger: 'blur' }]">
              <el-input v-model="form.name" placeholder="请输入计划名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划开始时间" prop="startTime"
              :rules="[{ required: true, message: '计划开始时间不能为空', trigger: 'change' }]">
              <el-date-picker v-model="form.startTime" style="width: 100%;" value-format="YYYY-MM-DD hh:mm:ss"
                type="datetime" placeholder="请选择开始时间" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划结束时间" prop="endTime"
              :rules="[{ required: true, message: '计划结束时间不能为空', trigger: 'change' }]">
              <el-date-picker v-model="form.endTime" style="width: 100%;" value-format="YYYY-MM-DD hh:mm:ss"
                type="datetime" placeholder="请选择结束时间" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="巡检类型" prop="inspectionType"
              :rules="[{ required: true, message: '巡检类型不能为空', trigger: 'change' }]">
              <el-select v-model="form.inspectionType" clearable placeholder="请选择巡检类型" @change="inspectionTypeChange">
                <el-option v-for="dict in inspection_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="巡检周期(天)" prop="inspectionCycle"
              :rules="[{ required: true, message: '巡检周期不能为空', trigger: 'blur' }]">
              <el-input-number v-model="form.inspectionCycle" :disabled="cycleDisabled" style="width:100%" :min="1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="巡检范围" prop="inspectionRange"
              :rules="[{ required: true, message: '巡检类型不能为空', trigger: 'change' }]" @change="inspectionRangeChange">
              <el-select v-model="form.inspectionRange" clearable placeholder="请选择巡检范围">
                <el-option v-for="dict in inspection_range" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="form.inspectionRange === 2" :span="8">
            <el-form-item label="道路点位" prop="ext1.roadSiteId"
              :rules="[{ required: true, message: '道路点位不能为空', trigger: 'change' }]">
              <el-select v-model="form.ext1.roadSiteId" clearable placeholder="请选择道路点位"
                @change="setInspectionItem($event, 'roadSite')">
                <el-option v-for="item in roadSiteOptions" :key="item.id" :label="item.name"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="form.inspectionRange === 3" :span="8">
            <el-form-item label="所属项目" prop="ext1.projectId"
              :rules="[{ required: true, message: '所属项目不能为空', trigger: 'change' }]">
              <el-select v-model="form.ext1.projectId" clearable placeholder="请选择所属项目"
                @change="setInspectionItem($event, 'project')">
                <el-option v-for="item in projectOptions" :key="item.id" :label="item.name"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="巡检员" prop="inspectionPersonId"
              :rules="[{ required: true, message: '巡检员不能为空', trigger: 'change' }]">
              <el-cascader v-model="form.inspectionPersonId" :props="{ emitPath: false }" :options="userOptions"
                placeholder="请选择巡检员" clearable :show-all-levels="false" @change="setUserInfo" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="联系电话" prop="ext1.phone">
              <el-input v-model="form.ext1.phone" disabled placeholder="选巡检员带出" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <SubTitle title="巡检内容" />
        <el-table :data="form.inspectionItem" max-height="300">
          <el-table-column label="设备类型名称" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.deviceTypeId" clearable placeholder="请选择设备类型名称"
                @change="deviceTypeChange(scope.$index, $event)">
                <el-option v-for="dict in dictGroup.deviceTypeOptions" :key="dict.id" :label="dict.name"
                  :value="dict.id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="设备编号" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.deviceIds" multiple collapse-tags clearable placeholder="请选择设备编号">
                <el-option v-for="dict in scope.row.deviceOptions" :key="dict.id" :label="dict.sn" :value="dict.id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="巡检项目" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.items" multiple collapse-tags clearable placeholder="请选择巡检项目">
                <el-option v-for="dict in scope.row.inspectionItemOptions" :key="dict.id" :label="dict.name"
                  :value="dict.id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="80">
            <template #header>
              <div class="operateBtn">
                <span>操作</span>
                <el-icon @click="addInspectionItem">
                  <CirclePlus />
                </el-icon>
              </div>
            </template>
            <template #default="scope">
              <el-icon @click="delInspectionItem(scope.$index)">
                <Delete />
              </el-icon>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm"> 确 定 </el-button>
          <el-button @click="cancel"> 取 消 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PatrolPlan" lang="ts">
import { listInspectionTeam, listInspectionItem, listInspectionTask, getInspectionTask, delInspectionTask, addInspectionTask, updateInspectionTask, listRoadSiteInfo } from '@/api/deviceCheck/index';
import {
  listDeviceType,
  getDeviceTypeDetailList
} from '@/api/deviceManage/deviceType';
import {
  listDevice,
  getDevice
} from '@/api/deviceManage/device';
import { listProjectInfo } from '@/api/projectManage/index';
import { deepClone } from '@/utils';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const tableList = ref([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const addFormRef = ref<ElFormInstance>();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const initFormData = {
  id: undefined,
  name: undefined,
  startTime: undefined,
  endTime: undefined,
  inspectionType: undefined,
  inspectionCycle: 1,
  status: 0,
  inspectionRange: undefined,
  inspectionPersonId: undefined,
  inspectionItem: [{
    deviceTypeId: undefined,
    deviceIds: [],
    items: [],
    deviceOptions: [],
    inspectionItemOptions:[]
  }],
  remark: undefined,
  ext1: <any>{
    phone: undefined,
    inspectionPersonName: undefined,
    roadSiteId: undefined,
    projectId: undefined,
  },
  ext2: undefined
};
const formData = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    status: undefined,
    params: {}
  }
});
const cycleDisabled = ref(false)
const { queryParams, form } = toRefs(formData);
const { inspection_type } = toRefs<any>(proxy?.useDict('inspection_type'));
const { inspection_range } = toRefs<any>(proxy?.useDict('inspection_range'));
const { inspection_status } = toRefs<any>(proxy?.useDict('inspection_status'));
const dictGroup = reactive({
  deviceTypeOptions: [],
})
const userOptions = ref([])
const roadSiteOptions = ref([])
const projectOptions = ref([])

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  const res = await listInspectionTask(queryParams.value);
  tableList.value = res.rows.map((item) => ({
    ...item,
    ext1: item.ext1 ? JSON.parse(item.ext1) : null,
  }));
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...deepClone(initFormData) };
  addFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增巡检计划';
};
/** 修改按钮操作 */
const handleUpdate = (row) => {
  reset();
  const _id = row?.id || ids.value[0];
  getInspectionTask(_id).then(({ data }) => {
    data.ext1 = data.ext1 && JSON.parse(data.ext1);
    data.inspectionItem = data.inspectionItem && JSON.parse(data.inspectionItem);
    Object.assign(form.value, data);
  });
  dialog.visible = true;
  dialog.title = '修改巡检计划';
};
const changeStatus = async (row, status) => {
  await updateInspectionTask({ id: row.id, status: status })
  const msg = status === '2' ? '停止成功' : '启动成功'
  proxy?.$modal.msgSuccess(msg);
  await getList();
}

/** 提交按钮 */
const submitForm = () => {
  addFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const { ext1, inspectionItem } = form.value;
      if (inspectionItem.length === 0) return proxy?.$modal.msgError('请添加巡检内容');
      let validFlag = false
      inspectionItem.forEach(item => {
        if (item.deviceTypeId === '' || item.deviceIds.length == 0 || item.items.length == 0) {
          validFlag = true
        }
      })
      if (validFlag) return proxy?.$modal.msgError('请选择补充巡检内容信息');
      buttonLoading.value = true;
      const params = Object.assign({}, form.value, { ext1: JSON.stringify(ext1), inspectionItem: JSON.stringify(inspectionItem) });
      if (form.value.id) {
        await updateInspectionTask(params).finally(() => (buttonLoading.value = false));
      } else {
        await addInspectionTask(params).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};
/** 删除按钮操作 */
const handleDelete = async (row) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除？').finally(() => (loading.value = false));
  await delInspectionTask(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};
const deviceTypeChange = (index, val) => {
  form.value.inspectionItem[index].deviceIds = []
  form.value.inspectionItem[index].items = []
  getDeviceList(index, val)
  getInspectionItem(index, val)
}
const getDeviceList = async (index, deviceTypeId) => {
  let deviceTypeDetailList = []
  form.value.inspectionItem[index].deviceOptions = []
  await getDeviceTypeDetailList({ deviceTypeId }).then(({ code, rows }) => {
    if (code === 200) {
      deviceTypeDetailList = rows
    }
  })
  deviceTypeDetailList.forEach(async (item) => {
    const res = await listDevice({ devTypeDetailId: item.id });
    if (res.code === 200) {
      form.value.inspectionItem[index].deviceOptions.push(...res.rows.map((item) => ({
        id: item.id,
        sn: item.sn,
      })))
    }
  })
};
const deviceTypeList = async () => {
  const res = await listDeviceType({});
  dictGroup.deviceTypeOptions = res.rows.map((item) => ({
    ...item,
    ext1: item.ext1 ? JSON.parse(item.ext1) : null
  }));
};
const getInspectionItem = (index,deviceTypeId) => {
  listInspectionItem({deviceTypeId}).then(({ code, rows }) => {
    if (code === 200) {
      form.value.inspectionItem[index].inspectionItemOptions = rows
    }
  })
}
const inspectionTypeChange = () => {
  if (form.value.inspectionType === '1') {
    form.value.inspectionCycle = 1
    cycleDisabled.value = true
  } else {
    cycleDisabled.value = false
  }
}
const setUserInfo = () => {
  form.value.ext1.phone = ''
  form.value.ext1.inspectionPersonName = ''
  const { inspectionPersonId } = form.value
  userOptions.value.forEach(item => {
    item.children.forEach(el => {
      if (inspectionPersonId === el.value) {
        form.value.ext1.phone = el.phone
        form.value.ext1.inspectionPersonName = el.label
      }
    })

  })
}
const getInspectionTeamList = async () => {
  const res = await listInspectionTeam({});
  res.rows.forEach((item) => {
    if (item.ext1) {
      item.ext1 = JSON.parse(item.ext1)
    }
    if (item.members) {
      item.members = JSON.parse(item.members)
    }
  });
  userOptions.value = res.rows.map(item => ({
    label: item.name,
    value: item.id,
    children: item.members.map(el => ({
      label: el.userName,
      value: el.userId,
      phone: el.phone
    }))
  }))
};
const addInspectionItem = () => {
  form.value.inspectionItem.push({
    deviceTypeId: undefined,
    deviceIds: [],
    items: [],
    deviceOptions: [],
    inspectionItemOptions:[]
  })
}
const delInspectionItem = (index) => {
  form.value.inspectionItem.splice(index, 1)
}
const getRoadSiteList = () => {
  listRoadSiteInfo({}).then(({ code, rows }) => {
    if (code === 200) {
      roadSiteOptions.value = rows
    }
  })
}
const getProjectList = () => {
  listProjectInfo({}).then(({ code, rows }) => {
    if (code === 200) {
      projectOptions.value = rows
    }
  })
}
const inspectionRangeChange = () => {
  form.value.inspectionItem = [{
    deviceTypeId: undefined,
    deviceIds: [],
    items: [],
    deviceOptions: [],
    inspectionItemOptions:[]
  }]
}
const setInspectionItem = (val, type) => {
  if (!val) return form.value.inspectionItem = []
  const options = type === 'roadSite' ? roadSiteOptions.value : projectOptions.value
  const [{ devices }] = options.filter(item => item.id === val)
  if (devices) {
    let deviceTypeObj = {}
    const tmpArr = devices.split(',')
    tmpArr.forEach(async (item, index) => {
      const { data } = await getDevice(item)
      const { deviceTypeId } = JSON.parse(data.ext1)
      if (deviceTypeObj[deviceTypeId]) {
        deviceTypeObj[deviceTypeId].push(item)
      } else {
        deviceTypeObj[deviceTypeId] = [item]
      }
      if (index == tmpArr.length - 1) {
        form.value.inspectionItem = []
        Object.keys(deviceTypeObj).forEach(async (key, ind) => {
          form.value.inspectionItem.push({
            deviceTypeId: key,
            deviceIds: deviceTypeObj[key],
            items: [],
            deviceOptions: [],
            inspectionItemOptions:[]
          })
          await getDeviceList(ind, key)
          await getInspectionItem(ind, key)
        })
      }
    })
  }
}
onMounted(() => {
  getList();
  deviceTypeList()
  getInspectionTeamList()
  getProjectList()
  getRoadSiteList()
});
</script>
<style lang="scss" scoped>
.operateBtn {
  display: flex;
  align-items: center;

  .el-icon {
    color: #409eff;
    margin-left: 5px;
    cursor: pointer;
  }
}
</style>
