<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input
            v-model="queryParams.taskName"
            placeholder="请输入任务名称"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="taskStatus">
        <el-select v-model="queryParams.taskStatus" placeholder="请选择任务状态" clearable>
          <el-option
              v-for="dict in dict.type.task_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="执行人" prop="executor">
        <el-input
            v-model="queryParams.executor"
            placeholder="请输入执行人"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="对象类型" prop="objType">
        <el-select v-model="queryParams.objType" placeholder="请选择巡检对象" clearable>
          <el-option
              v-for="dict in dict.type.obj_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['ems:inspection-task:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['ems:inspection-task:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['ems:inspection-task:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['ems:inspection-task:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inspectionTaskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务代码" align="left" prop="taskCode" width="160px"/>
      <el-table-column label="任务名称" align="left" prop="taskName" />
      <el-table-column label="巡检对象" align="center" prop="objName" >
        <template slot-scope="scope">
          <span><dict-tag :options="dict.type.obj_type" :value="scope.row.objType" />{{ "-" + scope.row.objName}}</span>
        </template>
      </el-table-column>

      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="执行人" align="center" prop="executor" />
      <el-table-column label="任务状态" align="center" prop="taskStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.task_status" :value="scope.row.taskStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-info" @click="handleInspection(scope.row)" v-hasPermi="['ems:inspection-task:edit']">
            巡检</el-button>
          <el-button size="mini" type="text"  icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['ems:inspection-task:edit']">
            修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" class="deleteBtn" @click="handleDelete(scope.row)" v-hasPermi="['basecfg:emsfacs:remove']">
            删除</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改巡检任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="任务代码" prop="taskCode" v-if="form.taskCode">
          <el-input v-model="form.taskCode" placeholder="请输入任务代码" disabled />
        </el-form-item>
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务状态" prop="taskStatus">
          <el-radio-group v-model="form.taskStatus">
            <el-radio
                v-for="dict in dict.type.task_status"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable
                          v-model="form.startTime"
                          type="datetime"
                          format="yyyy-MM-dd HH:mm"
                          value-format="yyyy-MM-dd HH:mm:00"
                          :style="{width: '100%'}"
                          placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable
                          v-model="form.endTime"
                          type="datetime"
                          format="yyyy-MM-dd HH:mm"
                          value-format="yyyy-MM-dd HH:mm:00"
                          :style="{width: '100%'}"
                          placeholder="请选择结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="执行人" prop="executor">
          <el-input v-model="form.executor" placeholder="请输入执行人" />
        </el-form-item>
        <el-form-item label="巡检对象" prop="objType">
          <el-radio-group v-model="form.objType" @input="onObjectCheck">
            <el-radio
                v-for="dict in taskObjType"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择巡检对象" prop="objCode">
          <el-select
              v-model="form.objCode"
              filterable
              remote
              reserve-keyword
              placeholder="请选择选择巡检对象"
              :remote-method="remoteMethod"
              :loading="loading"
              @change="onObjChange"
          >
            <el-option
                v-for="item in objOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="对象名称" prop="objName">
          <el-input v-model="form.objName" placeholder="请输入对象名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <report-form
        title="提交巡检报告"
        :ok-callback="onReportSubmit"
        :is-add="true"
        ref="reportForm"
        :task-info="form"
    >
    </report-form>
  </div>
</template>

<script>
import { listArea } from '@/api/basecfg/area';
import { listFacs } from '@/api/basecfg/emsfacs';
import { listZoning } from '@/api/basecfg/zoning';
import {
  addInspectionTask, delInspectionTask, getInspectionTask, listInspectionTask, updateInspectionTask,
} from '@/api/task/inspectionTask';
import { OBJ_TYPE } from '@/enums/DeviceFac';
import { TASK_TYPES } from '@/enums/TaskEnums';
import { copyObj } from '@/utils';
import ReportForm from '@/views/task/report/ReportForm.vue';

export default {
  name: 'InspectionTask',
  components: { ReportForm },
  dicts: ['task_status', 'obj_type', 'task_type', 'sys_job_group'],
  computed: {
    taskObjType() {
      const temp = copyObj(this.dict.type.obj_type);
      return _.remove(temp, (obj) => obj.value != OBJ_TYPE.devc.value);
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 巡检任务表格数据
      inspectionTaskList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      openInspection: false,
      objOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskCode: null,
        taskName: null,
        taskType: TASK_TYPES.manual.value,
        taskStatus: null,
        executor: null,
        objType: null,
        objName: null,
      },
      // 表单参数
      form: {
        taskType: TASK_TYPES.manual.value,
      },
      // 表单校验
      rules: {
        executor: [
          {
            required: true,
            message: '执行人不能为空',
            trigger: 'blur',
          },
        ],
        taskName: [
          {
            required: true,
            message: '任务名称不能为空',
            trigger: 'blur',
          },
        ],
        taskStatus: [
          {
            required: true,
            message: '任务状态不能为空',
            trigger: 'change',
          },
        ],
        startTime: [
          {
            required: true,
            message: '开始时间不能为空',
            trigger: 'blur',
          },
        ],
        endTime: [
          {
            required: true,
            message: '结束时间不能为空',
            trigger: 'blur',
          },
        ],
        objType: [
          {
            required: true,
            message: '巡检对象不能为空',
            trigger: 'change',
          },
        ],
        objCode: [
          {
            required: true,
            message: '选择巡检对象不能为空',
            trigger: 'change',
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    objHandle() {
      return {
        [OBJ_TYPE.fac.value]: async (param = {}) => {
          const {
            key = '',
            objCode = '',
          } = param;
          const { rows } = await listFacs({
            pageNum: 1,
            pageSize: 99,
            facsName: key,
            facsCode: objCode,
          });
          let result = [];
          if (rows.length > 0) {
            result = rows.map((item) => {
              return {
                value: item.facsCode,
                label: `${item.facsName}(${item.refAreaName})`,
              };
            });
          }
          this.objOptions = result;
        },
        [OBJ_TYPE.zone.value]: async (param = {}) => {
          const {
            key = '',
            objCode = '',
          } = param;
          const { rows } = await listZoning({
            pageNum: 1,
            pageSize: 99,
            zoningName: key,
            zoningCode: objCode,
          });
          let result = [];
          if (rows.length > 0) {
            result = rows.map((item) => {
              return {
                value: item.zoningCode,
                label: `${item.zoningName}(${item.areaPath},${item.usageDetail})`,
              };
            });
          }
          this.objOptions = result;
        },
        [OBJ_TYPE.area.value]: async (param = {}) => {
          const {
            key = '',
            objCode = '',
          } = param;
          const { rows } = await listArea({
            pageNum: 1,
            pageSize: 99,
            areaName: key,
            areaCode: objCode,
          });
          let result = [];
          if (rows.length > 0) {
            result = rows.map((item) => {
              return {
                value: item.areaCode,
                label: item.areaName,
              };
            });
          }
          this.objOptions = result;
        },
        [OBJ_TYPE.devc.value]: function () {},
      };
    },

    remoteMethod(key) {
      this.objHandle()[this.form.objType]({ key });
    },
    onObjChange(val) {
      const selectedOption = this.objOptions.find(option => option.value === val);
      this.form.objName = selectedOption ? selectedOption.label : '';
    },
    /** 查询巡检任务列表 */
    getList() {
      this.loading = true;
      listInspectionTask(this.queryParams).then(response => {
        this.inspectionTaskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskName: null,
        taskStatus: null,
        startTime: null,
        taskType: TASK_TYPES.manual.value,
        endTime: null,
        executor: null,
        objType: null,
        objCode: null,
        objName: null,
      };
      this.objOptions = [];
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加巡检任务';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getInspectionTask(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = '修改巡检任务';
        this.$nextTick(() => {
          this.objHandle()[this.form.objType]({ objCode: this.form.objCode });
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInspectionTask(this.form).then(response => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addInspectionTask(this.form).then(response => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除巡检任务编号为"' + ids + '"的数据项？').then(function () {
        return delInspectionTask(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess('删除成功');
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ems/inspectionTask/export', {
        ...this.queryParams,
      }, `inspectionTask_${new Date().getTime()}.xlsx`);
    },
    onReportSubmit() {
      this.$modal.msgSuccess('提交成功');
      this.openInspection = false;
      this.getList();
    },
    handleInspection(row) {
      const id = row.id;
      getInspectionTask(id).then(response => {
        this.form = response.data;
        this.$nextTick(() => {
          this.$refs.reportForm.show();
        });

      });
    },
    onObjectCheck(objType) {
      debugger
      this.objHandle()[objType]();
    },
  },
};
</script>
