<template>
  <div class="app-container">

    <!-- 列表 -->
    <AutoResizer :given-height="300">
      <template #default="{height}">
        <el-table
          v-if="columnsList.length > 0"
          v-loading="loading"
          :data="list"
          :height="height"
          border
        >
          <el-table-column
            v-if="columnsList[0].visible"
            :key="Math.random()"
            label="方案编码"
            align="center"
            prop="code"
          />
          <el-table-column
            v-if="columnsList[1].visible"
            :key="Math.random()"
            label="方案名称"
            align="center"
            prop="name"
          />
          <el-table-column
            v-if="columnsList[2].visible"
            :key="Math.random()"
            label="方案类型"
            align="center"
            prop="type"
          >
            <template slot-scope="scope">
              <dict-tag :type="DICT_TYPE.WMS_INSPECTION_CATEGORY" :value="scope.row.type" />
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[3].visible"
            :key="Math.random()"
            label="创建时间"
            align="center"
            prop="createTime"
            width="180"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="paramsQuery.auditStatus === 1 && columnsList[0].visible"
            :key="Math.random()"
            label="状态"
            align="center"
            prop="status"
          >
            <template slot-scope="{row}">
              <el-button
                v-if="row.status === 1"
                type="success"
                size="mini"
                @click="handleUpdateDisabled(row)"
              >已启用</el-button>
              <el-button
                v-else
                type="danger"
                size="mini"
                @click="handleUpdateEnable(row)"
              >已禁用</el-button>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="220"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                v-show="scope.row.auditStatus !== 1"
                v-hasPermi="['wms:material-item-master:update']"
                size="mini"
                type="text"
                icon="el-icon-check"
                :disabled="scope.row.status === 1 && scope.row.auditStatus === 1"
                @click="handleApproval(scope.row)"
              >{{ paramsQuery.auditStatus === -1 ? '提交' : '审核' }}</el-button>
              <el-button
                v-hasPermi="['wms:material-item:query']"
                size="mini"
                type="text"
                icon="el-icon-magic-stick"
                @click="handleUpdateInspectionCase(scope.row)"
              >检验方案</el-button>
              <el-button
                v-hasPermi="['wms:material-item-master:delete']"
                size="mini"
                type="text"
                class="text-danger"
                icon="el-icon-delete"
                :disabled="(scope.row.status === 1 && scope.row.auditStatus === 1)|| scope.row.auditStatus !== -1"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </AutoResizer>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 批核选择 -->
    <el-dialog
      title="审核"
      :visible.sync="auditVisible"
      width="30%"
      @close="auditClose"
    >
      <el-form
        ref="auditForm"
        :model="auditParams"
        size="small"
        label-width="98px"
        :rules="rules"
      >
        <el-row :gutter="20">
          <el-col>
            <el-form-item label="审核结果" prop="flag">
              <el-select v-model="auditParams.flag" clearable placeholder="请选择审核结果">
                <el-option
                  v-for="item in auditSelect"
                  :key="item.code"
                  :label="item.label"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item v-show="auditParams.flag === 0" label="驳回原因" prop="auditComment">
              <el-input
                v-model="auditParams.auditComment"
                type="textarea"
                :rows="2"
                placeholder="请输入驳回的原因"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="auditVisible = false">取 消</el-button>
        <el-button type="primary" @click="ensureApproval">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { getMaterialItemMasterPage, updateAllMaterialCase, deleteMaterialItemMaster } from '@/api/wms/quality/inspectionCase'
import { getFormColumnsList } from '@/api/system/saveColumns/index'
import { mapGetters } from 'vuex'
import { isArray } from 'min-dash'

export default {
  name: 'InspectionCaseTable',
  components: {
  },
  inject: ['paramsQuery'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 审核选择
      auditVisible: false,
      // 总条数
      total: 0,
      // WMS 品质管理-检验项管理列表
      list: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 审核提交的参数
      approvalObj: null,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10
      },
      // 审核参数
      auditParams: {
        flag: null,
        auditComment: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        flag: [{
          required: true,
          message: '请选择审批意见',
          trigger: 'blur'
        }]
      },
      // 批核选择
      auditSelect: [
        {
          label: '不通过',
          code: 0
        },
        {
          label: '通过',
          code: 1
        }
      ],
      // 显示隐藏列参数
      columns: [
        { key: 0, label: '方案编码', visible: true },
        { key: 1, label: '方案名称', visible: true },
        { key: 2, label: '方案类型', visible: true },
        { key: 3, label: '创建时间', visible: true }
      ],
      // 显示隐藏持久化参数
      columnsList: []
    }
  },
  computed: {
    ...mapGetters([
      'userId'
    ])
  },
  created() {
    // 获取显隐列列表
    this.getColumnsList()
    this.getList()
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true
      // 执行查询
      const params = {
        ...this.paramsQuery,
        ...this.queryParams
      }
      getMaterialItemMasterPage(params).then(response => {
        this.list = response.data.list
        this.total = response.data.total
      }).finally(() => {
        this.loading = false
      })
    },
    /** 取消按钮 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        inspectionNo: undefined,
        inspectionName: undefined,
        inspectionModel: undefined,
        inspectionType: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 修改检验方案
    handleUpdateInspectionCase(row) {
      this.reset()
      if (row) {
        this.$emit('updateInspectCase', row)
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // const id = row.id
      const { id, code } = row
      this.$modal.confirm('是否确认删除iqc检验方案编码为"' + code + '"的数据项?').then(function() {
        return deleteMaterialItemMaster(id)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    // 已启用行
    handleUpdateDisabled(row) {
      if (row) {
        this.$emit('updateDisabled', row)
      }
    },
    // 已禁用
    handleUpdateEnable(row) {
      if (row) {
        this.$emit('updateEnable', row)
      }
    },
    // 提交/审核
    handleApproval(row) {
      const { auditStatus, auditComment } = row
      this.approvalObj = row || {}
      this.auditParams.auditComment = auditComment
      auditStatus === -1 ? this.handleCommitOrApproval(row) : this.auditVisible = true
    },
    handleCommitOrApproval(row) {
      const { id, auditStatus } = row
      const params = {
        id,
        auditStatus: auditStatus === -1 ? 0 : this.auditParams.flag === 0 ? -1 : 1,
        auditComment: auditStatus === -1 ? undefined : this.auditParams.auditComment
      }
      updateAllMaterialCase(params).then(() => {
        const msg = auditStatus === -1 ? '提交成功' : '审批成功'
        this.auditVisible = false
        this.$modal.msgSuccess(msg)
        this.getList()
        this.$emit('submitCaseComplete')
      })
    },
    // 审核确定
    ensureApproval() {
      this.$refs['auditForm'].validate(valid => {
        if (!valid) {
          return
        }
        this.handleCommitOrApproval(this.approvalObj)
        this.auditParams.flag === 0 ? this.$emit('resetCaseApproval') : this.$emit('approvalCaseComplete')
      })
    },
    // 审核窗口关闭
    auditClose() {
      this.auditParams.flag = undefined
      this.auditParams.auditComment = null
    },
    // 获取显示隐藏列
    getColumnsList() {
      const { componentName } = this.$route.meta || null
      const params = {
        userId: this.userId,
        vueForm: componentName
      }
      getFormColumnsList(params).then(res => {
        if (isArray(res.data)) {
          this.columnsList = res.data.length === 0 ? this.columns : res.data
        } else {
          this.columnsList = this.columns
        }
      }).catch((err) => {
        if (err) {
          this.columnsList = this.columns
        }
      }).finally(() => {
        this.$emit('columns', this.columnsList)
      })
    }
  }
}
</script>

