<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务标题" prop="taskTitle">
        <el-input
          v-model="queryParams.taskTitle"
          placeholder="请输入任务标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务类型" prop="taskType">
        <el-select v-model="queryParams.taskType" placeholder="请选择任务状态" clearable size="small">
          <el-option
            v-for="item in workTaskType"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable size="small">
          <el-option
            v-for="item in workTaskStatus"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属单位" prop="createEnterpriseId">
        <el-select
          v-model="queryParams.createEnterpriseId"
          placeholder="请选择单位"
          :disabled="-2 != $store.state.user.enterpriseId"
        >
          <el-option
            v-for="item in enterprises"
            :key="item.enterpriseId"
            :label="item.enterpriseName"
            :value="item.enterpriseId"
          ></el-option>
        </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="['system: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="['system: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="['system:task:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:task:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList">
      <el-table-column label="任务标题" align="center" prop="taskTitle" width="200" :show-overflow-tooltip="true"/>
      <el-table-column label="任务类型" align="center" prop="taskType" :formatter="taskTypeFormatter"/>
      <el-table-column label="任务状态" align="center" prop="status" :formatter="taskStatusFormatter"/>
      <el-table-column label="所属单位" align="center" prop="createEnterpriseId" :formatter="enterpriseFormatter"/>
      <el-table-column label="开始时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.createTime">{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="截止时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.endTime">{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          <span v-else>-</span>
        </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-document"
            @click="handleDetail(scope.row)"
          >详情</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:task:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:task:remove']"
          >删除</el-button>
         <!-- <el-button
            size="mini"
            type="text"
            v-if="scope.row.status == '0'"
            @click="handleApproval(scope.row)"
            v-hasPermi="['system:task:edit']"
          >审批</el-button>-->
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.isReport == '0'"
            @click="report(scope.row)"
            v-hasPermi="['system:task:edit']"
          >上报</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="1000px" append-to-body destroy-on-close>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务标题" prop="taskTitle">
              <el-input v-model="form.taskTitle" placeholder="请输入任务标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务类型" prop="taskType">
              <el-select style="width: 100%" v-model="form.taskType" placeholder="请选择任务类型">
                <el-option
                  v-for="item in workTaskType"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue * 1"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="指定组" prop="groupNum">
              <el-select
                v-model="form.groupNum"
                filterable
                placeholder="请选择组号"
                style="width: 100%"
                clearable
                @change="changeGroup"
              >
                <el-option
                  v-for="item in linePatrolGroup"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                >
                </el-option>
              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="截止时间" prop="endTime">
              <el-date-picker
                style="width: 100%"
                clearable
                v-model="form.endTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择截止时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="任务内容" prop="taskContent">
          <!--<editor v-model="form.taskContent" :min-height="192"/>-->
          <el-input v-model="form.taskContent" :autosize="{ minRows: 5}" type="textarea" placeholder="请输入任务内容" />
        </el-form-item>

        <el-form-item label="人员选择">
          <PeopleChoice
            ref="changePaple"
            :disabled="isView"
            @getPeopleList="getPeopleList"
          />
        </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>

    <!-- 审核 -->
    <el-dialog title="审核信息" :visible.sync="approvalOpen" width="1000px" append-to-body destroy-on-close>
      <el-form ref="form" :model="form" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务标题" prop="taskTitle">
              {{form.taskTitle}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务类型" prop="taskType">
              {{taskTypeFormatter(form)}}
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="指定组">
              {{groupFormatter(form.groupNum)}}
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止时间">
             {{form.endTime}}
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="任务内容" prop="taskContent">
          <editor v-model="form.taskContent" :min-height="192" :readOnly="true"/>
        </el-form-item>

        <el-form-item label="选择人员">
          <PeopleChoice
            ref="changePapleApproval"
            :disabled="approvalView"
            @getPeopleList="getPeopleList"
          />
        </el-form-item>

        <el-form-item label="审批">
          <el-radio-group v-model="form.status" @change="approvalChange">
            <el-radio label="1">通过</el-radio>
            <el-radio label="2">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见">
          <el-input v-model="form.approvalSuggestion" type="textarea" placeholder="请输入审批意见" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="approvalSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask, exportTask } from "@/api/inspectionWork/workTask";
import Editor from '@/components/Editor';
import PeopleChoice from "./PeopleChoice";
import { enterpriseLists } from "@/api/regulation/info";
export default {
  name: "Task",
  components: {
    Editor,
    PeopleChoice,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 巡检巡查任务表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskType: null,
        taskTitle: null,
        taskContent: null,
        status: null,
        createEnterpriseId: null,
        endTime: null,
        isReport: null,
        isDel: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskTitle: [
          { required: true, message: "任务标题不能为空", trigger: "blur" }
        ],
        taskType: [
          { required: true, message: "请选择任务类型", trigger: "change" }
        ],
        groupNum : [
          { required: true, message: "请选择组", trigger: "change" }
        ],
        endTime: [
          { required: true, message: "请选择截止时间", trigger: "change" }
        ],
        taskContent: [
          { required: true, message: "任务内容不能为空", trigger: "change" }
        ],
      },
      workTaskType: [],
      workTaskStatus: [],
      isView: false,
      peopleList: [],
      isDetailOpen: false,
      detailTaskInfo: null,
      approvalOpen: false,
      approvalView: false,
      linePatrolGroup: [],
      enterprises: []
    };
  },
  created() {
    this.getEnterpriseLists();
    this.getList();
    this.getWorkTaskType();
    this.getWorkTaskStatus();
    if(-2 != this.$store.state.user.enterpriseId){
      this.queryParams.createEnterpriseId = this.$store.state.user.enterpriseId;
    }
  },
  methods: {
    /** 查询巡检巡查任务列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        taskId: null,
        taskType: null,
        taskTitle: null,
        taskContent: null,
        status: 0,
        createEnterpriseId: null,
        groupNum: null,
        createBy: null,
        createTime: null,
        endTime: null,
        isReport: null,
        isDel: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加巡检巡查任务";
      this.getLinePatrolGroup();
      this.$nextTick(() => {
          this.$refs.changePaple.changeNameList(null);
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const taskId = row.taskId || this.ids
      getTask(taskId).then(response => {
        this.form = response.data;
        this.getLinePatrolGroup();
        this.open = true;
        this.title = "修改巡检巡查任务";
        if(this.form.taskMemberList){
          this.$nextTick(() => {
              this.$refs.changePaple.changeNameList(this.form.taskMemberList);
              this.$refs.changePaple.getPersonList(this.form.groupNum);
          })
        }
      });
    },
    /**审批*/
    handleApproval(row){
      this.reset();
      const taskId = row.taskId || this.ids
      getTask(taskId).then(response => {
        this.form = response.data;
        this.getLinePatrolGroup();
        this.form.status = '1';
        this.approvalOpen = true;
        this.approvalView = true;
        if(this.form.taskMemberList){
          this.$nextTick(() => {
              this.$refs.changePapleApproval.changeNameList(this.form.taskMemberList);
              this.$refs.changePapleApproval.getPersonList(this.form.groupNum);
          })
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.peopleList.length < 1) {
            this.$message.error("请至少选择一个人员");
            return;
          }
          this.form.taskMemberList = this.peopleList;
          if (this.form.taskId != null) {
            updateTask(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.status = '1';
            addTask(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    approvalSubmit(){
      updateTask({taskId:this.form.taskId,status:this.form.status,approvalSuggestion:this.form.approvalSuggestion}).then(response => {
        this.msgSuccess("审核成功");
        this.approvalOpen = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const taskIds = row.taskId || this.ids;
      this.$confirm('是否确认删除巡检巡查任务标题为"' + row.taskTitle + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delTask(taskIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有巡检巡查任务数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportTask(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    getWorkTaskType(){
      this.getDicts("t_work_task_type").then(response => {
          this.workTaskType = response.data;
      });
    },
    getWorkTaskStatus(){
      this.getDicts("t_work_task_status").then(response => {
          this.workTaskStatus = response.data;
      });
    },
    getPeopleList(list){
      this.peopleList = list;
    },
    //任务类型
    taskTypeFormatter(row){
      return this.selectDictLabel(this.workTaskType, row.taskType);
    },
    //任务状态
    taskStatusFormatter(row){
      return this.selectDictLabel(this.workTaskStatus, row.status);
    },
    //详情
    handleDetail(row){
      if(row.taskType == '1'){
        this.$router.push({path:"taskPatrolDetail",query:{taskId:row.taskId}});
      }
      if(row.taskType == '2'){
        this.$router.push({path:"taskInspectDetail",query:{taskId:row.taskId}});
      }
    },
    approvalChange(){
      this.form.approvalSuggestion = '';
    },
    getLinePatrolGroup(){
      this.getDicts("t_line_patrol_group").then(response => {
          this.linePatrolGroup = response.data;
      });
    },
    changeGroup(val){
      this.$refs.changePaple.selectNameList = [];
      this.$refs.changePaple.getPersonList(val);
    },
    groupFormatter(groupNum){
      return this.selectDictLabel(this.linePatrolGroup, groupNum);
    },
    getEnterpriseLists(){
      enterpriseLists().then(response => {
        this.enterprises = response.rows;
        this.enterprises.push({enterpriseId:-2,enterpriseName:"政府部门"})
      });
    },
    enterpriseFormatter(row){
      let info = this.enterprises.find(item => item.enterpriseId == row.createEnterpriseId);
      return info?info.enterpriseName:"-";
    },
    report(row){
      this.$confirm('是否确认上报巡检巡查任务标题为"' + row.taskTitle + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return updateTask({taskId:row.taskId,isReport:"1"});
      }).then(() => {
          this.getList();
        this.msgSuccess("上报成功");
      }).catch(() => {});
    }
  }
};
</script>
