<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <el-select
          placeholder="请输入搜索设备名称"
          v-model="qParams.equipmentId"
          filterable
          clearable
          remote
          :remote-method="equipmentSearchRemoteHandle"
          :loading="equipmentSelectLoading"
          size="small"
          class="filter-item"
          style="width: 230px"
        >
          <el-option
            v-for="item in equipmentOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-input
            v-model="qParams.contentType"
            clearable
            size="small"
            placeholder="请输入保养内容"
            style="width: 200px"
            class="filter-item"
          />
        <el-input
            v-model="qParams.consumables"
            clearable
            size="small"
            placeholder="请输入消耗配件"
            style="width: 200px"
            class="filter-item"
          />
        <el-input
            v-model="qParams.maintenanceTeam"
            clearable
            size="small"
            placeholder="请输入维护保养队伍"
            style="width: 200px"
            class="filter-item"
          />
        <el-input
            v-model="qParams.supervisoryPerson"
            clearable
            size="small"
            placeholder="请输入监督人"
            style="width: 200px"
            class="filter-item"
          />
        <el-input
            v-model="qParams.accepter"
            clearable
            size="small"
            placeholder="请输入验收人"
            style="width: 200px"
            class="filter-item"
          />
        <span>
          <el-button
            class="filter-item"
            size="mini"
            type="success"
            icon="el-icon-search"
            @click="toQuery"
            >搜索</el-button
          >
          <el-button
            v-if="crud.optShow.reset"
            class="filter-item"
            size="mini"
            type="warning"
            icon="el-icon-refresh-left"
            @click="crud.resetQuery()"
            >重置</el-button
          >
          <el-button
            class="filter-item"
            type="export"
            icon="el-icon-download"
            size="mini"
            @click="open()"
            >导出浏览</el-button
          >
        </span>
      </div>
      <crudOperation :permission="permission"></crudOperation>
    </div>
    <!--表单组件-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible="crud.status.cu > 0"
      :title="crud.status.title"
      width="700px"
    >
      <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px">
        <el-row flex>
          <el-col :span="12">
            <el-form-item label="设备ID" prop="equipmentId">
              <el-select
                v-model="form.equipmentId"
                filterable
                clearable
                remote
                :remote-method="equipmentSelectRemoteHandle"
                :loading="equipmentSelectLoading"
                size="small"
                class="filter-item"
                style="width: 210px"
                @change="handleEquipmentIdChange"
              >
                <el-option
                  v-for="item in equipmentOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="设备型号" prop="model">
              <el-input v-model="form.model" disabled />
            </el-form-item>
            <el-form-item label="设备状态" prop="status">
              <el-input v-model="form.status"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="equipmentName">
              <el-input v-model="form.equipmentName" disabled />
            </el-form-item>
            <el-form-item label="运行时间" prop="runtimes">
              <el-input v-model="form.runtimes" />
            </el-form-item>
            <el-form-item label="保养内容" prop="contentType">
              <el-input v-model="form.contentType"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="实际维修内容（处理过程）" prop="actualContent">
            <el-input v-model="form.actualContent" type="textarea" rows="3"></el-input>
          </el-form-item>
          <el-form-item label="故障现象原因" prop="reasons">
            <el-input v-model="form.reasons" type="textarea" rows="3"></el-input>
          </el-form-item>
          <el-form-item label="配件消耗情况（名称+型号+数量分别描述）" prop="consumables">
            <el-input v-model="form.consumables" type="textarea" rows="4"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="维修保养日期" prop="maintenanceDate">
              <el-date-picker
                type="date"
                v-model="form.maintenanceDate"
                value-format="yyyy-MM-dd"
                size="small"
                style="width: 210px"
                @change="handleDateChange"
              />
            </el-form-item>
            <el-form-item label="维修队伍" prop="maintenanceTeam">
              <el-input v-model="form.maintenanceTeam"></el-input>
            </el-form-item>
            <el-form-item label="维修人" prop="maintenancePerson">
              <el-input v-model="form.maintenancePerson"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="完成日期" prop="finishDate">
              <el-date-picker
                type="date"
                v-model="form.finishDate"
                value-format="yyyy-MM-dd"
                size="small"
                style="width: 210px"
                @change="handleDateChange"
              />
            </el-form-item>
            <el-form-item label="监督人" prop="supervisoryPerson">
              <el-input v-model="form.supervisoryPerson"></el-input>
            </el-form-item>
            <el-form-item label="验收人" prop="accepter">
              <el-input v-model="form.accepter"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="submitRecord"
          >确认</el-button
        >
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      style="width: 100%"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        v-for="item in maintenanceRecordTableOptions"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
        :width="item.width"
        :align="item.align"
        :fixed="item.fixed"
        :sortable="item.sortable"
      >
      </el-table-column>
      <!--   编辑与删除   -->
      <el-table-column
        v-if="checkPer(['admin', 'equipment:maintenance:edit', 'equipment:maintenance:del'])"
        label="操作"
        width="130px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <div style="display: flex">
            <udOperation :data="scope.row" :permission="permission" />
            <el-button
              slot="reference"
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="toDelete(scope.row)"
            />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <!-- <pagination /> -->
  </div>
</template>

<script>
import permission from '@/directive/permission'
import crudReport from '@/api/system/report'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import { initData } from '@/api/data'
import { getOptions } from '@/api/equipment/public'
import crudComps from '@crud'
import { maintenanceRecordTableOptions } from '../tableConfig'

const defaultForm = {
  id: 0,
  equipmentId: null, //设备id
  equipmentName: '', //设备名称
  code: '', //设备编号
  model: '', //设备型号
  runtimes: null, //运行时间
  contentType: '', //保养内容
  actualContent: '', //实际保养内容
  reasons: '', //现象与原因
  consumables: '', //配件消耗情况
  maintenanceDate: null, //维保日期
  finishDate: null, //完成日期
  maintenanceTeam: '', //维修保养队伍
  maintenancePerson: '', //维修保养人
  supervisoryPerson: '', //监督人
  accepter: '', //验收人
  status: '', //设备状态
  remark: '', //备注
}

export default {
  name: 'EquipmentMaintenanceRecord',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: { ...crudComps },
  cruds() {
    return CRUD({
      title: '设备维修保养记录',
      url: 'report/data/getList',
      query: {
        sql: 'select * from equipment_maintenance_record where 1=1',
      },
      listOrder: [],
      crudMethod: { ...crudReport },
      optShow: {
        add: true,
        edit: true,
        del: false,
        reset: true,
        import: false,
        export: false,
      },
    })
  },
  computed: {
    crudCU() {
      return this.crud.status.cu > 0
    },
    VUE_APP_BASE_API() {
      return process.env.VUE_APP_BASE_API
    },
  },
  data() {
    return {
      maintenanceRecordTableOptions,
      viewLoading: false,
      permission: {
        add: ['admin', 'equipment:maintenance:add'],
        edit: ['admin', 'equipment:maintenance:edit'],
      },
      rules: {
        equipmentId: [{ required: true, message: '请选择设备', trigger: 'blur' }],
        contentType: [{ required: true, message: '请填写保养内容', trigger: 'blur' }],
        actualContent: [{ required: true, message: '请填写实际保养内容', trigger: 'blur' }],
        reasons: [{ required: true, message: '请填写故障现象与原因', trigger: 'blur' }],
        consumables: [{ required: true, message: '请填写配件消耗情况', trigger: 'blur' }],
        maintenancePerson: [{ required: true, message: '请填写维修保养人', trigger: 'blur' }],
        supervisoryPerson: [{ required: true, message: '请填写监督人', trigger: 'blur' }],
      },
      equipmentOptions: [{ label: '无', value: '0' }],
      equipmentSelectLoading: false,
      obj: {
        tableName: 'equipment_maintenance_record',
        primaryKey: 'id',
        fields: [],
      },
      qParams: {
        equipmentId: null,
        contentType: '', //保养内容
        actualContent: '', //实际保养内容
        reasons: '', //现象与原因
        consumables: '', //配件消耗情况
        maintenanceDate: null, //维保日期
        finishDate: null, //完成日期
        maintenanceTeam: '', //维修保养队伍
        maintenancePerson: '', //维修保养人
        supervisoryPerson: '', //监督人
        accepter: '', //验收人
      },
    }
  },
  created() {},
  methods: {
    async refreshRecord(sql) {
      try {
        const res = await initData('report/data/getList', { sql: sql })
        this.crud.data = res.data.content
      } catch (err) {
        console.log(err)
      }
    },
    toQuery() {
      var str = 'select * from equipment_maintenance_record where 1=1 '
      if (this.qParams.equipmentId && this.qParams.equipmentId.length == 18) {
        str = str + 'and equipmentId = ' + this.qParams.equipmentId
      }
      if (this.qParams.contentType && this.qParams.contentType !== '') {
        str = str + "and contentType like '%" + this.qParams.contentType + "%'"
      }
      if (this.qParams.consumables && this.qParams.consumables !== '') {
        str = str + "and consumables like '%" + this.qParams.consumables + "%'"
      }
      if (this.qParams.maintenanceTeam && this.qParams.maintenanceTeam !== '') {
        str = str + "and maintenanceTeam like '%" + this.qParams.maintenanceTeam + "%'"
      }
      if (this.qParams.supervisoryPerson && this.qParams.supervisoryPerson !== '') {
        str = str + "and supervisoryPerson like '%" + this.qParams.supervisoryPerson + "%'"
      }
      if (this.qParams.accepter && this.qParams.accepter !== '') {
        str = str + "and accepter like '%" + this.qParams.accepter + "%'"
      }
      try {
        this.refreshRecord(str)
      } catch (error) {
        console.log(err)
      }
    },
    //提交前校验
    beforeSubmit() {
      if (!this.form.equipmentId && this.form.equipmentId.length < 17) return false
      if (!this.form.contentType && this.form.contentType == '') return false
      if (!this.form.actualContent && this.form.actualContent == '') return false
      if (!this.form.reasons && this.form.reasons == '') return false
      if (!this.form.consumables && this.form.consumables == '') return false
      if (!this.form.maintenancePerson && this.form.maintenancePerson == '') return false
      if (!this.form.supervisoryPerson && this.form.supervisoryPerson == '') return false
      return true
    },
    //提交数据
    async submitRecord() {
      if (this.beforeSubmit()) {
        try {
          if (this.form.id && this.form.id > 0) {
            this.obj = {
              tableName: 'equipment_maintenance_record',
              primaryKey: 'id',
              fields: [this.form],
            }
          } else {
            this.obj = {
              tableName: 'equipment_maintenance_record',
              fields: [
                {
                  equipmentId: this.form.equipmentId,
                  equipmentName: this.form.equipmentName,
                  code: this.form.code,
                  model: this.form.model,
                  runtimes: this.form.runtimes,
                  contentType: this.form.contentType,
                  actualContent: this.form.actualContent,
                  reasons: this.form.reasons,
                  consumables: this.form.consumables,
                  maintenanceDate: this.form.maintenanceDate,
                  finishDate: this.form.finishDate,
                  maintenanceTeam: this.form.maintenanceTeam,
                  maintenancePerson: this.form.maintenancePerson,
                  supervisoryPerson: this.form.supervisoryPerson,
                  accepter: this.form.accepter,
                  status: this.form.status,
                  remark: this.form.remark,
                },
              ],
            }
          }
          const res = await initData('Report/Data/Save', this.obj)
          this.crud.cancelCU()
          // console.log(res)
        } catch (err) {
          console.log(err)
        }
      } else {
        this.$message.error('请正确填写维修保养记录！')
      }
    },
    //删除数据
    async doDelete(data) {
      try {
        this.obj = {
          tableName: 'equipment_maintenance_record',
          primaryKey: 'id',
          fields: [{ id: data.id }],
        }
        const res = await initData('Report/Data/delete', this.obj)
      } catch (err) {
        console.log(err)
      }
    },
    toDelete(data) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.doDelete(data).then(() => this.toQuery())
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    handleDateChange(v) {
      console.log(v)
    },
    //动态搜索选择设备
    async handleEquipmentIdChange() {
      try {
        const res = await initData('equipment/ledger/getEntity', { id: this.form.equipmentId })
        // console.log(res)
        this.form.equipmentName = res.data.name
        this.form.model = res.data.model
        this.form.code = res.data.code
        this.form.status = res.data.statusStr
      } catch (err) {
        console.log(err)
      }
    },
    equipmentSelectRemoteHandle(value) {
      if (value && value.length > 2) {
        this.equipmentSelectLoading = true
        getOptions('Equipment', { id: this.form.equipmentId, codeOrName: value })
          .then((res) => {
            this.equipmentOptions = res.data.content
            this.equipmentSelectLoading = false
          })
          .catch((err) => {
            this.equipmentOptions = [{ label: '无', value: '0' }]
            this.equipmentSelectLoading = false
          })
      } else {
        this.equipmentOptions = [{ label: '无', value: '0' }]
        this.equipmentSelectLoading = false
      }
    },
    equipmentSearchRemoteHandle(value) {
      if (value && value.length > 2) {
        this.equipmentSelectLoading = true
        getOptions('Equipment', { id: this.qParams.equipmentId, codeOrName: value })
          .then((res) => {
            this.equipmentOptions = res.data.content
            this.equipmentSelectLoading = false
          })
          .catch((err) => {
            this.equipmentOptions = [{ label: '无', value: '0' }]
            this.equipmentSelectLoading = false
          })
      } else {
        this.equipmentOptions = [{ label: '无', value: '0' }]
        this.equipmentSelectLoading = false
      }
    },
    getOptions() {
      Object.keys(this.optionsObj).forEach(async (key) => {
        try {
          let res = await getOptions(key)
          if (res.code === 20000) this.optionsObj[key] = res.data.content
        } catch (error) {
          console.log(error)
        }
      })
    },
    open() {
      window.open('/reporttool/run?reportName=/设备维修档案.cr')
    },
  },
}
</script>

<style lang="scss" scoped></style>
