<template>
  <div class="app-container">
    <el-card class="topCard">
      <div class="topDiv">
        <span style="">工位号：</span>
        <el-select v-model="stationNumberValue" placeholder="请选择工位号" clearable size="small" style="width: 240px">
          <el-option
            v-for="item in stationNumber"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            size="mini"/>
        </el-select>
        <span style="margin-left: 20px;">产品型号：</span>
        <el-select v-model="productCodeValue" placeholder="请选择产品型号" clearable size="small" style="width: 200px">
          <el-option
            v-for="item in productTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            size="mini"/>
        </el-select>
        <span style="margin-left: 20px;">检测项目：</span>
        <el-input v-model="testItemKeyword" placeholder="输入检测项目关键字" clearable size="small" style="width: 200px"/>
        <el-button type="primary" icon="el-icon-search" size="small" style="margin-left: 20px;" @click="getTableData()">查询</el-button>
        <el-button type="primary" plain icon="el-icon-plus" size="small" style="margin-left: 20px;" @click="addStationParams()">增加</el-button>
        <el-button :loading="exportLoading" :disabled="exportLoading" type="warning" plain icon="el-icon-download" size="small" style="margin-left: 20px;" @click="exportExcel">导出</el-button>
      </div>
      <div style="margin-top: 5px">
        <el-table
          v-loading="loading"
          ref="multipleTable"
          :data="tableData"
          :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          element-loading-text="数据加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.2)"
          class="main"
          tooltip-effect="dark"
          height="630px"
          style="width: 100%"
          border
          size="mini">
          <el-table-column type="index" width="60" label="序号" align="center"/>
          <el-table-column align="center" label="工位号" width="100">
            <template slot-scope="scope">
              {{ scope.row.工位号 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="工位名称" width="100">
            <template slot-scope="scope">
              {{ scope.row.工位名称 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="产品型号" width="120">
            <template slot-scope="scope">
              {{ scope.row.产品型号 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="检测项目">
            <template slot-scope="scope">
              {{ scope.row.检测项目 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="项目类型" width="140">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.项目类型 === 0" type="success" size="mini">常规项目</el-tag>
              <el-tag v-if="scope.row.项目类型 === 1" type="warning" size="mini">送检项目</el-tag>
              <el-tag v-if="scope.row.项目类型 === 2" type="info" size="mini">设备采集</el-tag>
              <el-tag v-if="scope.row.项目类型 === 3" type="primary" size="mini">拍照上传</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="检测项目代码" width="150">
            <template slot-scope="scope">
              {{ scope.row.检测项目代码 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="实测项目代码" width="150">
            <template slot-scope="scope">
              {{ scope.row.实测项目代码 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="是否必填" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.必填 === 1 || scope.row.必填 === '1'" type="danger" size="mini">必填</el-tag>
              <el-tag v-else type="info" size="mini">非必填</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="上限值" width="100">
            <template slot-scope="scope">
              {{ scope.row.上限值 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="下限值" width="100">
            <template slot-scope="scope">
              {{ scope.row.下限值 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="单位" width="100">
            <template slot-scope="scope">
              {{ scope.row.单位 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="判定标准" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.数据类型 === 1" type="success" size="mini">定量</el-tag>
              <el-tag v-if="scope.row.数据类型 === 0" type="warning" size="mini">定性</el-tag>
              <el-tag v-if="scope.row.数据类型 === 2" type="info" size="mini">文本</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-edit" size="small" @click="editInformation(scope.row)"/>
              <el-button type="text" icon="el-icon-delete" size="small" style="color: #ff0000" @click="deleteParamsInformation(scope.row)"/>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <el-dialog :visible.sync="dialogFormVisible_AddOrEditParams" :title="title_Params" center style="min-height: 230px;" width="800px">
      <el-form ref="form_stationParams" :model="form_stationParams" :rules="rules_stationParams" label-position="right" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="工位号" prop="工位号" style="display: inline-block">
              <el-select v-model="form_stationParams.工位号" size="small" placeholder="请选择工位号" style="width: 240px">
                <el-option
                  v-for="item in stationNumber"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品型号" prop="产品代码" style="display: inline-block">
              <el-select v-model="form_stationParams.产品代码" size="small" placeholder="请选择产品型号" @change="onProductChange">
                <el-option
                  v-for="item in productTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检测项目" prop="检测项目" style="display: inline-block">
              <el-input v-model="form_stationParams.检测项目" clearable size="small" placeholder="请输入检测项目" style="width: 230px"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检测项目代码" prop="检测项目代码" style="display: inline-block">
              <el-input v-model="form_stationParams.检测项目代码" clearable size="small" placeholder="请输入检测项目代码" style="width: 230px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目类型" prop="项目类型" style="display: inline-block">
              <el-select v-model="form_stationParams.项目类型" size="small" placeholder="请选择项目类型">
                <el-option
                  v-for="item in ProjectTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="实测项目代码" prop="实测项目代码" style="display: inline-block">
              <el-input v-model="form_stationParams.实测项目代码" clearable size="small" placeholder="请输入实测项目代码" style="width: 230px"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否必填" prop="标准值" style="display: inline-block">
              <el-select v-model="form_stationParams.标准值" size="small" placeholder="请选择是否必填" style="width: 230px">
                <el-option :label="'必填'" :value="1" />
                <el-option :label="'非必填'" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="单位" style="display: inline-block">
              <el-input v-model="form_stationParams.单位" clearable size="small" placeholder="请输入单位" style="width: 230px"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="结果判定" prop="数据类型" style="display: inline-block">
              <el-select v-model="form_stationParams.数据类型" size="small" placeholder="请选择结果判定类型">
                <el-option
                  v-for="item in ParamsType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div>
              定性：人工点选是否合格；
            </div>
            <div>
              定量：根据上下限值自动判定是否合格
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item v-if="form_stationParams.数据类型 === '1'" label="上限值" prop="上限值" style="display: inline-block">
              <el-input-number v-model="form_stationParams.上限值" :min="form_stationParams.下限值" :step="0.1" size="small" placeholder="请输入上限值" style="width: 230px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form_stationParams.数据类型 === '1'" label="下限值" prop="下限值" style="display: inline-block">
              <el-input-number v-model="form_stationParams.下限值" :max="form_stationParams.上限值" :step="0.1" size="small" placeholder="请输入下限值" style="width: 230px"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="callOff_AddOrEditParams('form_stationParams')">取消</el-button>
        <el-button v-if="title_Params === '添加参数'" type="primary" size="small" @click="submitAdd_Params('form_stationParams')">确定</el-button>
        <el-button v-if="title_Params === '修改参数'" type="primary" size="small" @click="submitEdit_Params('form_stationParams')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form_stationParams: {
        ID: 0,
        工位号: '',
        产品型号: '',
        产品代码: null,
        检测项目: '',
        检测项目代码: '',
        实测项目代码: '',
        标准值: 0, // 1 必填，0 非必填
        上限值: 0,
        下限值: 0,
        单位: '',
        数据类型: '',
        项目类型: 0
      },
      rules_stationParams: {
        工位号: [{ required: true, message: '工位号不能为空', trigger: 'blur' }],
        产品代码: [{ required: true, message: '产品型号不能为空', trigger: 'change' }],
        检测项目: [{ required: true, message: '检测项目不能为空', trigger: 'blur' }],
        检测项目代码: [{ required: true, message: '检测项目代码不能为空', trigger: 'blur' }],
        标准值: [{ required: true, message: '是否必填不能为空', trigger: 'change' }],
        上限值: [{ required: false, message: '上限值不能为空', trigger: 'blur' }],
        下限值: [{ required: false, message: '下限值不能为空', trigger: 'blur' }],
        数据类型: [{ required: true, message: '数据类型不能为空', trigger: 'blur' }],
        项目类型: [{ required: true, message: '项目类型不能为空', trigger: 'change' }]
      },
      stationNumberValue: '',
      stationNumber: [],
      productCodeValue: null,
      productTypes: [],
      testItemKeyword: '',
      title_Params: '',
      dialogFormVisible_AddOrEditParams: false,
      loading: false,
      exportLoading: false,
      ParamsType: [
        {
          label: '定量',
          value: '1'
        },
        {
          label: '定性',
          value: '0'
        },
        {
          label: '文本',
          value: '2'
        }
      ],
      ProjectTypeOptions: [
        { label: '常规项目', value: 0 },
        { label: '送检项目', value: 1 },
        { label: '设备采集', value: 2 },
        { label: '拍照上传', value: 3 }
      ],
      tableData: [],
      tableDataParams: [],
      expandsDetail: [],
      expandedRows: null
    }
  },
  created() {
    this.getStationNumber()
    this.getProductTypes()
    this.getTableData()
  },
  methods: {
    getProductTypes() {
      const param = []
      this.productTypes = []
      const Data = this.CreateData('11', 'CATL_基础_整机_产品代码_查询', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.productTypes.push({
            label: response.data[i]['产品名称'],
            value: response.data[i]['产品代码']
          })
        }
      })
    },
    onProductChange(val) {
      // 当产品型号变化时，同步设置产品型号名称
      const found = this.productTypes.find(item => item.value === val)
      this.form_stationParams.产品型号 = found ? found.label : ''
    },
    getStationNumber() {
      this.stationNumber = []
      var param = []
      var Data = this.CreateData('11', '电子看板_质量数据_首件数据_工位表_查询', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.stationNumber.push({
            label: `【${response.data[i].工位号}】${response.data[i].工位名称}`,
            value: response.data[i].工位号
          })
        }
      })
    },

    getQueryParam() {
      var param = []
      param.push(['工位号', this.stationNumberValue])
      param.push(['产品代码', this.productCodeValue])
      param.push(['检测项目', this.testItemKeyword])
      return param
    },
    getTableData() {
      this.loading = true
      var param = this.getQueryParam()
      var Data = this.CreateData('11', '电子看板_质量数据_首件数据_基础表_查询', param)
      this.ExecDatabase(Data).then(response => {
        this.tableData = []
        if (response.data.length !== 0) {
          this.tableData = response.data
        }
        this.loading = false
      }).catch(error => {
        this.tableData = []
        this.loading = false
        this.$message.error('数据加载失败，请稍后重试！')
        console.error('Error fetching interface data:', error)
      })
    },
    exportExcel() {
      if (this.tableData.length === 0) {
        this.$message.warning('暂无数据')
        return
      }

      var exportData = JSON.parse(this.CreateData('2005', '电子看板_质量数据_首件数据_基础表_查询', this.getQueryParam()))
      exportData.exportFileName = '首件检测项维护'
      exportData.exportColumns = '工位号,工位名称,产品型号,检测项目,项目类型,检测项目代码,实测项目代码,必填=是否必填,上限值,下限值,单位,数据类型=判定标准'
      var Data = JSON.stringify(exportData)
      this.runExcelExport(Data, 'exportLoading')
    },
    addStationParams() {
      this.title_Params = '添加参数'
      this.dialogFormVisible_AddOrEditParams = true
      this.$nextTick(() => {
        this.$refs['form_stationParams'].resetFields()
        // 默认非必填
        this.form_stationParams.标准值 = 0
      })
    },
    editInformation(row) {
      this.title_Params = '修改参数'
      this.form_stationParams.ID = row.ID
      this.form_stationParams.工位号 = row.工位号
      this.form_stationParams.产品型号 = row.产品型号
      this.form_stationParams.产品代码 = row.产品代码
      this.form_stationParams.检测项目 = row.检测项目
      this.form_stationParams.检测项目代码 = row.检测项目代码
      this.form_stationParams.实测项目代码 = row.实测项目代码
      // 是否必填从后端返回的必填字段映射
      this.form_stationParams.标准值 = Number(row.必填)
      this.form_stationParams.上限值 = row.上限值
      this.form_stationParams.下限值 = row.下限值
      this.form_stationParams.单位 = row.单位
      this.form_stationParams.数据类型 = String(row.数据类型)
      this.form_stationParams.项目类型 = row.项目类型
      this.dialogFormVisible_AddOrEditParams = true
    },
    deleteParamsInformation(row) {
      this.$confirm('是否删除该参数？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var param = []
        param[0] = ['ID', row.ID]
        var Data = this.CreateData('12', '电子看板_质量数据_首件数据_基础表_删除', param)
        this.ExecDatabase(Data).then(response => {
          if (response.data[0].result === '1') {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getTableData()
          } else {
            this.$message.error('删除失败！')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    submitAdd_Params(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          var param = []
          param[0] = ['工位号', this.form_stationParams.工位号]
          param[1] = ['产品型号', this.form_stationParams.产品型号]
          param[2] = ['产品代码', this.form_stationParams.产品代码]
          param[3] = ['检测项目', this.form_stationParams.检测项目]
          param[4] = ['检测项目代码', this.form_stationParams.检测项目代码]
          param[5] = ['实测项目代码', this.form_stationParams.实测项目代码 === '' ? null : this.form_stationParams.实测项目代码]
          // 必填标识传给存储过程的@必填参数
          param[6] = ['必填', this.form_stationParams.标准值]
          param[7] = ['上限值', this.form_stationParams.上限值]
          param[8] = ['下限值', this.form_stationParams.下限值]
          param[9] = ['单位', this.form_stationParams.单位]
          param[10] = ['数据类型', this.form_stationParams.数据类型]
          param[11] = ['项目类型', this.form_stationParams.项目类型]
          var Data = this.CreateData('11', '电子看板_质量数据_首件数据_基础表_增加', param)
          this.ExecDatabase(Data).then(response => {
            if (response.data[0].result === 1) {
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              // 连续添加：保留工位号/产品型号/项目类型/数据类型/是否必填
              const keepStation = this.form_stationParams.工位号
              const keepProductCode = this.form_stationParams.产品代码
              const keepProductName = this.form_stationParams.产品型号
              const keepProjectType = this.form_stationParams.项目类型
              const keepDataType = this.form_stationParams.数据类型
              const keepRequired = this.form_stationParams.标准值
              this.form_stationParams.ID = 0
              this.form_stationParams.工位号 = keepStation
              this.form_stationParams.产品代码 = keepProductCode
              this.form_stationParams.产品型号 = keepProductName
              this.form_stationParams.检测项目 = ''
              this.form_stationParams.检测项目代码 = ''
              this.form_stationParams.实测项目代码 = ''
              this.form_stationParams.标准值 = keepRequired
              this.form_stationParams.上限值 = 0
              this.form_stationParams.下限值 = 0
              this.form_stationParams.单位 = ''
              this.form_stationParams.数据类型 = keepDataType
              this.form_stationParams.项目类型 = keepProjectType
              this.$nextTick(() => {
                if (this.$refs['form_stationParams']) {
                  this.$refs['form_stationParams'].clearValidate()
                }
              })
              this.getTableData()
            } else if (response.data[0].result === 2) {
              this.$message.error(response.data[0].message || '该参数代码已存在，请重新输入！')
            } else {
              this.$message.error('添加失败！')
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    submitEdit_Params(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          var param = []
          param[0] = ['工位号', this.form_stationParams.工位号]
          param[1] = ['产品型号', this.form_stationParams.产品型号]
          param[2] = ['产品代码', this.form_stationParams.产品代码]
          param[3] = ['检测项目', this.form_stationParams.检测项目]
          param[4] = ['检测项目代码', this.form_stationParams.检测项目代码]
          param[5] = ['实测项目代码', this.form_stationParams.实测项目代码 === '' ? null : this.form_stationParams.实测项目代码]
          // 必填标识传给存储过程的@必填参数
          param[6] = ['必填', this.form_stationParams.标准值]
          param[7] = ['上限值', this.form_stationParams.上限值]
          param[8] = ['下限值', this.form_stationParams.下限值]
          param[9] = ['单位', this.form_stationParams.单位]
          param[10] = ['数据类型', this.form_stationParams.数据类型]
          param[11] = ['ID', this.form_stationParams.ID]
          param[12] = ['项目类型', this.form_stationParams.项目类型]
          var Data = this.CreateData('11', '电子看板_质量数据_首件数据_基础表_编辑', param)
          this.ExecDatabase(Data).then(response => {
            if (response.data[0].result === 1) {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.dialogFormVisible_AddOrEditParams = false
              this.getTableData()
            } else if (response.data[0].result === 2) {
              this.$message.error(response.data[0].message || '该参数代码已存在，请重新输入！')
            } else {
              this.$message.error('修改失败！')
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    callOff_AddOrEditParams(form) {
      this.$refs[form].resetFields()
      this.dialogFormVisible_AddOrEditParams = false
    }
  }
}
</script>

<style>
.topCard{
  margin: 5px;
}
.topDiv{
  margin-bottom: 10px;
}
</style>
