<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
<!--      <el-form-item label="项目类别" prop="projectCode">-->
<!--        <Treeselect v-model="queryParams.typeId" :options="$refs.projectType?$refs.projectType.treeData:[]" placeholder="请选择" :props="{value:'id'}" :show-count="true" style="width:200px;" />-->
<!--      </el-form-item>-->
      <el-form-item label="项目编号" prop="projectCode">
        <el-input
          v-model="queryParams.projectCode"
          placeholder="请输入项目编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </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>

    <projectType type="1" ref="projectType" @child-click="handleNodeClick" v-if="type==1">
      <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="['business:maintainProject:add']"
          >新增</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="['business:maintainProject: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="['business:maintainProject:export']"
          >导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-hasPermi="['business:maintainProject:import']"
          >导入</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="maintainProjectList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" type="index" />
        <el-table-column label="维修项目类别" align="center" prop="typeName" />
        <el-table-column label="维修项目编号" align="center" prop="projectCode" />
        <el-table-column label="维修项目名称" align="center" prop="projectName" />
        <el-table-column label="维修标准工时" align="center" prop="standardManHour" />
        <el-table-column label="维修标准单价" align="center" prop="standardPrice" />
        <el-table-column label="技术规范" align="center" prop="technicalSpecification" :show-overflow-tooltip="true" />
        <el-table-column label="保修期" align="center" prop="warrantyPeriod" />
        <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-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['business:maintainProject:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['business:maintainProject: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"
      />
    </projectType>
    <div v-else>
      <el-table v-loading="loading" :data="maintainProjectList" ref="selectionTable" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" type="index" />
        <el-table-column label="维修项目类别" align="center" prop="typeName" />
        <el-table-column label="维修项目编号" align="center" prop="projectCode" />
        <el-table-column label="维修项目名称" align="center" prop="projectName" />
        <el-table-column label="维修标准工时" align="center" prop="standardManHour" />
        <el-table-column label="维修标准单价" align="center" prop="standardPrice" />
        <el-table-column label="技术规范" align="center" prop="technicalSpecification" :show-overflow-tooltip="true" />
        <el-table-column label="保修期" align="center" prop="warrantyPeriod" />
      </el-table>

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

    <!-- 添加或修改维修项目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <div class="app-title">维修项目信息</div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="维修类型" prop="typeId">
              <Treeselect v-model="form.typeId" :options="$refs.projectType?$refs.projectType.treeData:[]" placeholder="请选择" style="width: 100%;" :props="{value:'id'}" :show-count="true" @select='handleChange' />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="维修名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入维修名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="维修编号" prop="projectCode">
              <el-input v-model="form.projectCode" placeholder="维修编号自动生成" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="维修标准工时" prop="standardManHour">
              <el-input v-model="form.standardManHour" :min="0" type="number" placeholder="维修标准工时">
                  <template slot="append">时</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="维修标准单价" prop="standardPrice">
              <el-input v-model="form.standardPrice" :min="0" type="number" placeholder="维修标准单价">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保修期" prop="warrantyPeriod">
              <el-input v-model="form.warrantyPeriod" :min="0" type="number" placeholder="保修期" @input="form.warrantyPeriod=form.warrantyPeriod.replace(/\D/g,'')">
                <template slot="append">天</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="技术规范" prop="technicalSpecification">
              <el-input v-model="form.technicalSpecification" placeholder="请输入技术规范" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="关联故障项目" prop="malfunctionProjectList">
              <el-select v-model="form.malfunctionProjectList" filterable placeholder="请选择关联故障项目（多选）" style="width: 100%;" multiple>
                <el-option v-for="item in guanlianList" :key="item.id" :value="item.id" :label="item.malfunctionName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="app-title">系统信息</div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="创建人" prop="createBy">
              <el-input v-model="form.createBy" placeholder="请输入创建人" style="width: 100%;" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker v-model="form.createTime" type="datetime" value-formatter="yyyy-MM-dd HH:mm:ss" placeholder="选择创建时间" disabled>
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--          <div class="el-upload__tip" slot="tip">-->
          <!--            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据-->
          <!--          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMaintainProject, getMaintainProject, delMaintainProject, addMaintainProject, updateMaintainProject } from "@/api/business/maintainProject";
import {listMalfunctionProject, listMalfunctionProjectAll} from "@/api/business/malfunctionProject";
import { formatDate } from "@/utils/index"
import { getProjectType } from "@/api/business/projectType";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

import projectType from "../projectType/index"
import { getToken } from '@/utils/auth'

export default {
  name: "MaintainProject",
  components:{
    Treeselect,
    projectType,
  },
  props:{
    notInProjectIds: {},
    type: {
      type: String,
      default: '1'
    }
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 维修项目表格数据
      maintainProjectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/maintainProject/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        typeId: undefined,
        projectCode: undefined,
        projectName: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        id: [
          { required: true, message: "主键不能为空", trigger: "blur" }
        ],
        typeId: [
          { required: true, message: "维修类型不能为空", trigger: "change" }
        ],
        typeName: [
          { required: true, message: "维修类型名称不能为空", trigger: "blur" }
        ],
        projectName: [
          { required: true, message: "维修项目名称不能为空", trigger: "blur" }
        ],
        standardManHour: [
          { required: true, message: "维修标准工时不能为空", trigger: "blur" }
        ],
        standardPrice: [
          { required: true, message: "维修标准单价不能为空", trigger: "blur" }
        ],
        warrantyPeriod: [
          { required: true, message: "保修期不能为空", trigger: "blur" }
        ],
        technicalSpecification: [
          { required: true, message: "技术规范不能为空", trigger: "blur" }
        ],
        state: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
        isDelete: [
          { required: true, message: "是否删除不能为空", trigger: "blur" }
        ],
        malfunctionProjectList: [
          { required: true, message: "关联故障项目不能为空", trigger: "change" }
        ],
      },
      guanlianList: [],
      selectList: [],
    };
  },
  created() {
    this.getList();
    // this.getGuanlian()
  },
  methods: {
    getGuanlian(){
      listMalfunctionProjectAll().then(res=>{
        this.guanlianList = res.data;
      })
    },
    /** 查询维修项目列表 */
    getList() {
      this.loading = true;
      listMaintainProject({ ...this.queryParams, notInIdList: this.notInProjectIds }).then(response => {
        this.maintainProjectList = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        typeId: undefined,
        typeName: undefined,
        projectCode: undefined,
        projectName: undefined,
        standardManHour: undefined,
        standardPrice: undefined,
        warrantyPeriod: undefined,
        technicalSpecification: undefined,
        state: undefined,
        createBy: this.$store.state.user.userInfo.userName,
        createTime: formatDate(new Date().getTime()),
        updateBy: undefined,
        updateTime: undefined,
        isDelete: undefined,
        malfunctionProjectList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.typeId = undefined;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.selectList = [...selection]
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 节点点击 */
    handleNodeClick(item) {
      this.queryParams.typeId = item.id;
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加维修项目";
      this.getGuanlian()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      this.getGuanlian()
      const id = row.id || this.ids
      getMaintainProject(id).then(response => {
        if(response.data.malfunctionProjectList)response.data.malfunctionProjectList=response.data.malfunctionProjectList.map(item=>item.id);
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改维修项目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form);
          let params={...this.form}
          params.malfunctionProjectList=params.malfunctionProjectList?params.malfunctionProjectList.map(item=>{
            let item1=this.guanlianList.find(item2=>item2.id==item)
            return {id: item1.id,malfunctionName:item1.malfunctionName}
          }):[]
          delete params.createBy;
          delete params.createTime;
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateMaintainProject(params).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addMaintainProject(params).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除维修项目，删除后无法恢复！').then(() => {
        this.loading = true;
        return delMaintainProject(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/maintainProject/export', {
        ...this.queryParams
      }, `维修项目`)
    },
    /** 模板按钮操作 */
    handleStencil() {
      this.download("business/maintainProject/importTemplate", {}, `维修项目模板`);
    },
    handleChange(e){
      this.$refs.form.clearValidate('typeId');
      getProjectType(e.id).then(res=>{
        this.form.typeName=res.data.typeName
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "维修项目导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('business/maintainProject/importTemplate', {}, `维修项目导入模板`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>

<style scoped>
.app-title{
  font-size: 16px;
  font-weight: 600;
  padding: 10px 0;
}
</style>
