<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               :search.sync="search"
               header-cell-class-name="header-class"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.workorder_delete" @click="handleDelete">批量删除</el-button>
      </template>
      <template slot="menuRight">
        <el-button type="primary" size="small" plain @click="handleDetailAdd" v-if="permission.workorder_add">新增</el-button>
        <el-button type="primary" size="small" plain @click="handleReject" v-if="permission.workorder_reject">批量驳回</el-button>
        <el-button type="primary" size="small" plain @click="handleAuditing" v-if="permission.workorder_audit">批量审核</el-button>
        <el-button type="primary" size="small" plain @click="handleExport" v-if="permission.workorder_export">导出</el-button>
      </template>
      <template #menu="{row,index}">
        <el-button @click="handleDetailSearch(row,index)" type="text" size="small" icon="el-icon-view" v-if="permission.workorder_view">查看详情</el-button>
        <el-button @click="openDialog(row)" type="text" size="small" icon="el-icon-upload2" v-if="permission.workorder_uploadRes">上传处理结果</el-button>
        <el-button @click="rowDel(row)" type="text" size="small" icon="el-icon-delete" v-if="permission.workorder_delete">删 除</el-button>
      </template>
    </avue-crud>
    <el-dialog title="上传处理结果" width="35%" :visible.sync="dialogFormVisible" :before-close="closeDialog">
      <el-form :model="dialogForm" ref="dialogForm">
        <el-form-item label="处理时间" :label-width="formLabelWidth">
          <el-col :span="24">
            <el-date-picker v-model="dialogForm.processingTime" type="datetime" placeholder="选择日期时间" size="small" autocomplete="off" style="width: 350px"></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="发生原因" :label-width="formLabelWidth">
          <el-col :span="24">
            <el-input v-model="dialogForm.description" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" maxlength="400" show-word-limit size="small" autocomplete="off" style="width: 350px"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="结束时间" :label-width="formLabelWidth">
          <el-col :span="24">
           <el-date-picker v-model="dialogForm.endTime" type="datetime" placeholder="选择日期时间" size="small" autocomplete="off" style="width: 350px"></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="处理结果" :label-width="formLabelWidth">
          <el-col :span="24">
            <el-select v-model="dialogForm.handlingResult" size="small" placeholder="请选择处理结果" style="width: 350px">
              <el-option
                v-for="op in processResOptions"
                :key="op.value"
                :label="op.label"
                :value="op.value"
              ></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="处理结果描述" :label-width="formLabelWidth">
          <el-col :span="24">
            <el-input v-model="dialogForm.processDescription" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" maxlength="400" size="small" show-word-limit autocomplete="off" style="width: 350px"></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" size="small" :loading="loading">取消</el-button>
        <el-button type="primary" @click="submitForm" size="small" :loading="loading">确定</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, reject, auditing} from "@/api/smart/workorder";
  import {getDictData} from "@/api/system/dict";
  import {getToken} from "@/util/auth";
  import expUtil from "@/util/exportUtil";
  import {mapGetters} from "vuex";

  export default {
    data() {
      return {
        form: {},
        search:{},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          searchIndex: 3,
          searchIcon: true,
          align: 'center',
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          refreshBtn: false,
          searchShowBtn: false,
          menuWidth: 270,
          menuAlign: 'center',
          column: [
            {
              label: "主键",
              prop: "id",
              hide: true,
              rules: [{
                required: true,
                message: "请输入主键",
                trigger: "blur"
              }]
            },
            {
              label: 'KKS编码',
              prop: 'equipmentLedgerId',
              type: 'select',
              remote: true,
              search: true,
              props: {
                label: 'kksEncoding',
                value: 'id',
                // desc: 'station'
              },
              hide: true,
              dicUrl: "/api/equipmentledger/listByCoding?coding={{key}}",
            },
            {
              label: "KKS编码",
              prop: "kksEncoding"
            },
            {
              label: "场站",
              prop: "station",
              type: "select",
              search: true,
              hide: true,
              dicUrl: "/api/daf-system/dict/dictionary?code=station",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入场站",
                trigger: "blur"
              }]
            },
            {
              label: "工单编号",
              prop: "workOrderNo",
              search: true,
              rules: [{
                required: true,
                message: "请输入工单编号",
                trigger: "blur"
              }]
            },
            {
              label: "内容描述",
              prop: "description",
              search: true,
              rules: [{
                required: true,
                message: "请输入内容描述",
                trigger: "blur"
              }]
            },
            {
              label: "工单类型",
              prop: "workOrderType",
              type: "select",
              dicUrl: "/api/daf-system/dict/dictionary?code=workorder_type",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              search: true,
              rules: [{
                required: true,
                message: "请输入工单类型",
                trigger: "blur"
              }]
            },
            {
              label: "维护作业类型",
              prop: "maintenanceTaskType",
              span: 8
            },
            {
              label: "所属场站",
              prop: "plannedFactory",
              rules: [{
                required: true,
                message: "请输入所属场站",
                trigger: "blur"
              }]
            },
            {
              label: "责任人",
              prop: "managerUserName",
              rules: [{
                required: true,
                message: "请输入负责人",
                trigger: "blur"
              }]
            },
            {
              label: "责任班组",
              prop: "responsibilityTeam",
              search: true,
              rules: [{
                required: true,
                message: "请输入责任班组",
                trigger: "blur"
              }]
            },
            {
              label: "用户状态",
              prop: "userStatus",
              type: "select",
              search: true,
              hide: true,
              dicUrl: "/api/daf-system/dict/dictionary?code=user_status",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入用户状态",
                trigger: "blur"
              }]
            },
            {
              label: "发生时间",
              prop: "occurrenceTime",
              hide: true,
              rules: [{
                required: true,
                message: "请输入发生时间",
                trigger: "blur"
              }]
            },
            {
              label: "执行班组",
              prop: "taskTeam",
              hide: true,
              rules: [{
                required: true,
                message: "请输入执行班组",
                trigger: "blur"
              }]
            },
            {
              label: "处理时间",
              prop: "processingTime",
              hide: true,
              rules: [{
                required: true,
                message: "请输入处理时间",
                trigger: "blur"
              }]
            },
            {
              label: "发生原因",
              prop: "causeIncident",
              hide: true,
              rules: [{
                required: true,
                message: "请输入发生原因",
                trigger: "blur"
              }]
            },
            {
              label: "处理过程描述",
              prop: "processDescription",
              hide: true,
              rules: [{
                required: true,
                message: "请输入处理过程描述",
                trigger: "blur"
              }]
            },
            {
              label: "结束时间",
              prop: "endTime",
              hide: true,
              rules: [{
                required: true,
                message: "请输入结束时间",
                trigger: "blur"
              }]
            },
            {
              label: "工单完成",
              prop: "handlingResult",
            },
            {
              label: "审核状态",
              prop: "approvalStatus",
              type: "select",
              dicUrl: "/api/daf-system/dict/dictionary?code=check_status",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入审核状态",
                trigger: "blur"
              }]
            }
          ]
        },
        data: [],
        dialogFormVisible: false,
        dialogForm: {
          id: null,
          processDescription: null,
          handlingResult: null,
          endTime: null,
          description: null,
          processingTime: null
        },
        formLabelWidth: '120px',
        processResOptions: []
      };
    },
    created() {
      this.remoteMethod('workorder_process_res');
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: false,
          viewBtn: false,
          delBtn: false,
          editBtn: false
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      handleDetailAdd() {
        this.$router.push({
          path: "/workorder/detail",
          query: {
            frameMode:"add"
          },
        });
      },
      handleDetailSearch(row) {
        this.$router.push({
          path: "/workorder/detail",
          query: {
            frameMode:"search",
            id: row.id
          },
        });
      },
      handleAuditing() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("是否将选择数据审核?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return auditing(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleReject() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("是否将选择数据审核?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return reject(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      handleExport() {
        this.$confirm("是否导出数据?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          expUtil.excelExportEasy(`/api/workorder/export?daf-auth=${getToken()}`, this.search);
        });
      },
      remoteMethod(query) {
        this.processResOptions = [];
        if (query !== '') {
          this.loading = true;
          getDictData(query).then(res => {
            this.loading = false;
            if (res && res.data && res.data.data) {
              this.processResOptions = res.data.data.map(item => {
                return { value: item.dictKey, label: `${item.dictValue}` };
              });
            }
          });
        }
      },
      openDialog(row) {
        this.dialogFormVisible = true;
        this.$nextTick(() => {
          this.dialogForm.id = row.id;
          this.dialogForm.processDescription = row.processDescription;
          this.dialogForm.handlingResult = row.handlingResult;
          this.dialogForm.endTime = row.endTime;
          this.dialogForm.description = row.description;
          this.dialogForm.processingTime = row.processingTime;
        });
      },
      closeDialog() {
        this.$confirm('确认关闭？')
          .then(_ => {
            this.$refs.dialogForm.resetFields();
            this.$nextTick(() => {
              this.loading = false;
              this.dialogFormVisible = false;
            });
            return true;
          })
          .catch(_ => {
            return false;
          });
      },
      submitForm() {
        this.loading = true;
        var formData = {...this.dialogForm};
        update(formData).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.loading = false;
          this.dialogFormVisible = false;
        }, error => {
          window.console.log(error);
          this.loading = false;
          this.dialogFormVisible = false;
        });
      }
    }
  };
</script>

<style>
</style>
