<template>
  <div class="app-container" style="padding: 0;">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="type==1">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            :disabled="isDelivery == 1"
            @click="handleAdd"
            v-hasPermi="['business:repairFormProject: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:repairFormPeoject:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="repairFormProjectList" :show-summary="type==1" :summary-method="getSummaries" @selection-change="handleSelectionChange">
      <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="examineUserCode" v-if="type==2" />
      <el-table-column label="检验人员名称" align="center" prop="examineUserName" v-if="type==2"/>
<!--      <el-table-column label="检验人员" align="center" prop="examineUserId" width="200" v-if="type==2">-->
<!--        <template slot-scope="scope">-->
<!--          <el-select v-model="scope.row.examineUserId" filterable>-->
<!--            <el-option v-for="item in maintainUserList" :key="item.id" :value="item.id">{{`${item.jobNumber}-${item.name}`}}</el-option>-->
<!--          </el-select>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="检验时间" align="center" prop="examineTime" width="220" v-if="type==2" />
<!--      <el-table-column label="检验时间" align="center" prop="examineTime" width="220" v-if="type==2">-->
<!--        <template slot-scope="scope">-->
<!--          <el-date-picker-->
<!--              v-model="scope.row.examineTime"-->
<!--              type="datetime"-->
<!--              value-formatter="yyyy-MM-dd HH:mm:ss"-->
<!--              placeholder="选择检验时间"-->
<!--              style="width: 100%"-->
<!--          />-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="维修标准工时" align="center" prop="standardManHour" v-if="type==1"/>
      <el-table-column label="维修标准单价（元）" align="center" prop="standardPrice" v-if="type==1"/>
      <el-table-column label="维修标准小计（元）" align="center" prop="totalMoney" v-if="type==1" >
        <template slot-scope="scope">
          {{scope.row.totalMoney = (scope.row.standardManHour * scope.row.standardPrice).toFixed(1)}}
        </template>
      </el-table-column>
      <el-table-column label="实际维修总工时" align="center" prop="actualTime" v-if="type==1"/>
      <el-table-column label="技术规范" align="center" prop="technicalSpecification" v-if="type==1"/>
      <el-table-column label="保修期（天）" align="center" prop="warrantyPeriod" v-if="type==1"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleExamine(scope.row)"
            :disabled="isDelivery == 1 || scope.row.examineTime != undefined"
            v-if="type==2"
          >检验</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-if="type==1"
            :disabled="isDelivery == 1"
            v-hasPermi="['business:repairFormProject:edit']"
          >派工</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-if="type==1"
            :disabled="isDelivery == 1"
            v-hasPermi="['business:repairFormProject:remove']"
            style="color: #ff4949;"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改报修单-维修项目\检验项目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1300px" append-to-body destroy-on-close>
     <el-form :model="queryMaintainParams" ref="queryMaintainForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="项目类别" prop="projectCode">
          <Treeselect v-model="queryMaintainParams.typeId" :options="typeTreeData" placeholder="请选择" :props="{value:'id'}" :show-count="true" style="width:200px;" />
        </el-form-item>
        <el-form-item label="项目编号" prop="projectCode">
          <el-input
              v-model="queryMaintainParams.projectCode"
              placeholder="请输入项目编号"
              clearable
              @keyup.enter.native="handleMaintainQuery"
          />
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input
              v-model="queryMaintainParams.projectName"
              placeholder="请输入项目名称"
              clearable
              @keyup.enter.native="handleMaintainQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleMaintainQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetMaintainQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getMaintainList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="maintainProjectList" max-height="450px" @selection-change="handleMaintainSelectionChange">
        <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="maintainTotal>0"
          :total="maintainTotal"
          :page.sync="queryMaintainParams.pageNum"
          :limit.sync="queryMaintainParams.pageSize"
          @pagination="getMaintainList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm1">确 定</el-button>
        <el-button :loading="buttonLoading" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="派工" :visible.sync="open1" width="80%" append-to-body destroy-on-close>
      <el-form ref="form" :model="form" :rules="rules" label-width="115px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="班组名称">
              <el-input v-model="form.groupName" placeholder="请输入" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="维修项目名称">
              <el-input v-model="form.projectName" placeholder="请输入" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="维修项目工时">
              <el-input v-model="form.standardManHour" placeholder="请输入" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <repairFormProjectDispatch ref="projectDispatch" :data="form" />
      <div slot="footer" class="dialog-footer">
<!--        <el-button :loading="buttonLoading" type="primary" @click="submitForm2">确 定</el-button>-->
        <el-button @click="open1 = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="检验人员" :visible.sync="open2" width="400px" append-to-body destroy-on-close>
      <el-form ref="examineForm" :model="examineForm" :rules="examineRules" label-width="100px">
        <el-col>
          <el-form-item label="检验人员" prop="examineUserId">
            <el-select v-model="examineForm.examineUserId" filterable style="width: 100%">
              <el-option v-for="item in maintainUserList" :key="item.id" :value="item.id" :label="`${item.jobNumber}-${item.name}`">{{`${item.jobNumber}-${item.name}`}}</el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="检验时间" prop="examineTime">
            <el-date-picker style="width: 100%;"
                            v-model="examineForm.examineTime"
                            type="datetime"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="请选择">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm3">确 定</el-button>
        <el-button @click="open2 = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRepairFormProject,
  getRepairFormProject,
  delRepairFormProject,
  addRepairFormProject,
  updateRepairFormProject,
  addRepairFormProjectP,
  examineRepairFormProject
} from '@/api/business/repairFormProject'
import { getSiteGroup } from "@/api/business/siteGroup";
import maintainProject from "../maintainProject/index";
import repairFormProjectDispatch from "../repairFormProjectDispatch/index";
import { addRepairFormProjectDispatchP } from '@/api/business/repairFormProjectDispatch'
import projectType from '@/views/business/projectType/index.vue'
import Treeselect from '@riophae/vue-treeselect'
import { listMaintainProject } from '@/api/business/maintainProject'
import { getTree } from '@/api/business/projectType'
import { listUser } from '@/api/business/user'

export default {
  name: "RepairFormProject",
  components: { Treeselect, projectType, maintainProject, repairFormProjectDispatch },
  props:{
    type: {},
    repairFormId:{},
    groupId:{},
    groupName:{},
    isDelivery:{},
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      maintainTotal: 0,
      // 报修单-维修项目\检验项目表格数据
      repairFormProjectList: [],
      maintainProjectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      open2: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 1000,
        repairFormId: undefined,
        typeId: undefined,
        typeName: undefined,
        projectCode: undefined,
        projectName: undefined,
        standardManHour: undefined,
        standardPrice: undefined,
        warrantyPeriod: undefined,
        technicalSpecification: undefined,
        actualTime: undefined,
        isDispatch: undefined,
        examineUserId: undefined,
        examineUserCode: undefined,
        examineUserName: undefined,
        examineTime: undefined,
      },
      // 查询参数
      queryMaintainParams: {
        pageNum: 1,
        pageSize: 1000,
        typeId: undefined,
        typeName: undefined,
        projectCode: undefined,
        projectName: undefined,
        standardManHour: undefined,
        standardPrice: undefined,
        warrantyPeriod: undefined,
        technicalSpecification: undefined,
        state: undefined,
        isDelete: undefined
      },
      // 表单参数
      form: {},
      examineForm: {},
      // 维修项目勾选
      typeTreeData: [],
      maintainProjectSelectList: [],
      maintainUserList: [],
      // 表单校验
      rules: {
        id: [
          { required: true, message: "主键不能为空", trigger: "blur" }
        ],
        repairFormId: [
          { required: true, message: "报修单ID不能为空", trigger: "blur" }
        ],
        typeId: [
          { required: true, message: "维修类型ID不能为空", trigger: "blur" }
        ],
        typeName: [
          { required: true, message: "维修类型名称不能为空", trigger: "blur" }
        ],
        projectCode: [
          { 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" }
        ],
        actualTime: [
          { required: true, message: "实际维修总工时不能为空", trigger: "blur" }
        ],
        isDispatch: [
          { required: true, message: "是否已派工不能为空", trigger: "blur" }
        ],
        examineUserId: [
          { required: true, message: "检验人员ID不能为空", trigger: "blur" }
        ],
        examineUserCode: [
          { required: true, message: "检验人员编号不能为空", trigger: "blur" }
        ],
        examineUserName: [
          { required: true, message: "检验人员名称不能为空", trigger: "blur" }
        ],
        examineTime: [
          { required: true, message: "检验时间不能为空", trigger: "blur" }
        ],
      },
      examineRules: {
        examineUserId: [
          { required: true, message: "检验人员不能为空", trigger: "blur" }
        ],
        examineTime: [
          { required: true, message: "检验时间不能为空", trigger: "blur" }
        ],
      },
      open1: false,
    };
  },
  created() {
    if (this.repairFormId) {
      this.getList();
    }
    if (this.type == 2) {
      this.getMaintainUserList()
    }
  },
  methods: {
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (index !== 1 && index !== 2 && index !== 3 && index !== 8 && index !== 9 && index !== 10 ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += '';
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    /** 查询报修单-维修项目\检验项目列表 */
    getList() {
      this.loading = true;
      listRepairFormProject({ ...this.queryParams, repairFormId: this.repairFormId }).then(response => {
        this.repairFormProjectList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询维修项目列表 */
    getMaintainList() {
      this.loading = true;
      listMaintainProject({ ...this.queryMaintainParams }).then(response => {
        this.maintainProjectList = response.rows;
        this.total = response.total;
        this.loading = false;
      })
    },
    getTypeTree(){
      getTree(1).then(res=>{
        this.typeTreeData = res.data
      })
    },
    /** 查询人员-人员列表 */
    getMaintainUserList() {
      listUser({ type: 1, pageNum: 1, pageSize: 1000 }).then(response => {
        this.maintainUserList = response.rows;
      });
    },
    /** 搜索按钮操作 */
    handleMaintainQuery() {
      this.queryMaintainParams.pageNum = 1;
      this.getMaintainList();
    },
    /** 重置按钮操作 */
    resetMaintainQuery() {
      this.queryMaintainParams={
        pageNum: 1,
        pageSize: this.queryMaintainParams.pageSize,
        typeId: undefined,
        projectCode: undefined,
        projectName: undefined,
      }
      this.resetForm("queryMaintainForm");
      this.handleMaintainQuery();
    },
    // 多选框选中数据
    handleMaintainSelectionChange(selection) {
      this.maintainProjectSelectList = selection
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        repairFormId: undefined,
        typeId: undefined,
        typeName: undefined,
        projectCode: undefined,
        projectName: undefined,
        standardManHour: undefined,
        standardPrice: undefined,
        warrantyPeriod: undefined,
        technicalSpecification: undefined,
        actualTime: undefined,
        isDispatch: undefined,
        examineUserId: undefined,
        examineUserCode: undefined,
        examineUserName: undefined,
        examineTime: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
      };
      this.examineForm = {
        repairFormId: undefined,
        id: undefined,
        examineUserId: undefined,
        examineTime: undefined
      };
      this.resetForm("form");
      this.resetForm("examineForm");
    },
    /** 搜索按钮操作 */
    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 = "添加维修项目";
      this.getMaintainList()
      this.getTypeTree()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.form = {...row,groupId: this.groupId, groupName: this.groupName, repairFormId: this.repairFormId, repairFormProjectId: row.id};
      this.open1 = true;
      this.title = "派工";
    },
    /** 检验按钮操作 */
    handleExamine(row) {
      this.open2 = true;
      this.reset();
      this.examineForm = {
        id: row.id,
        examineUserId: row.examineUserId,
        examineTime: row.examineTime,
        repairFormId: row.repairFormId,
        maintainId: row.maintainId
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateRepairFormProject(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addRepairFormProject(this.form).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('是否确认维修项目编号为"' + row.projectCode + '"的数据项？').then(() => {
        this.loading = true;
        return delRepairFormProject(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    submitForm1(){
      if(this.maintainProjectSelectList){
        this.buttonLoading = true;
        addRepairFormProjectP({ repairFormId: this.repairFormId, maintainIdList: this.maintainProjectSelectList.map(item=>item.id) }).then(res=>{
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        }).finally(() => {
            this.buttonLoading = false;
          });
      }else{
        this.$message.error('至少选择一项');
      }
    },
    /** 提交按钮 */
    submitForm3() {
      this.$refs["examineForm"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.examineForm.id != null) {
            examineRepairFormProject(this.examineForm).then(response => {
              this.$modal.msgSuccess("检验成功");
              this.open2 = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    // 派工-确定
    submitForm2(){
      if(this.$refs.projectDispatch.repairFormProjectDispatchList){
        let projectDispatchList = this.$refs.projectDispatch.repairFormProjectDispatchList.map(item =>{
          return{
            maintainUserId: item.id,
            dispatchManHour: item.dispatchManHour,
            deductManHour: item.deductManHour,
            actualManHour: item.actualManHour,
          }
        })
        this.buttonLoading = true;
        addRepairFormProjectDispatchP({ projectId: this.form.repairFormProjectId, projectDispatchList: projectDispatchList }).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open1 = false;
          this.getList();
        }).finally(() => {
          this.buttonLoading = false;
        });
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/repairFormProject/export', {
        ...this.queryParams
      }, `repairFormProject_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>
