<template>
  <div class="app-container">
    <el-card class="topCard">
      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="特殊工位定义维护" name="definition">
          <div class="topDiv">
            <span>类型：</span>
            <el-input v-model="definitionSearch.type" placeholder="模糊搜索" clearable size="small" style="width: 180px" @keyup.enter.native="handleDefinitionSearch" />
            <span style="margin-left: 10px">工位列表：</span>
            <el-input v-model="definitionSearch.opList" placeholder="模糊搜索" clearable size="small" style="width: 220px" @keyup.enter.native="handleDefinitionSearch" />
            <el-button type="primary" plain size="small" icon="el-icon-search" style="margin-left: 10px" @click="handleDefinitionSearch">查询</el-button>
            <el-button type="success" plain size="small" icon="el-icon-plus" @click="handleDefinitionAdd">新增</el-button>
            <el-button :loading="definitionExportLoading" :disabled="definitionExportLoading" type="warning" plain size="small" icon="el-icon-download" @click="exportDefinitionExcel">导出</el-button>
          </div>

          <el-table
            v-loading="definitionLoading"
            :data="definitionTableData"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
            element-loading-text="数据加载中"
            style="width: 100%"
            max-height="650px"
            border
            size="mini">
            <el-table-column align="center" type="index" width="60" label="序号" />
            <el-table-column align="center" prop="type" label="类型" width="220" show-overflow-tooltip />
            <el-table-column align="center" prop="opList" label="工位列表" show-overflow-tooltip />
            <el-table-column align="center" label="操作" width="160" fixed="right">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleDefinitionEdit(scope.row)">编辑</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" style="color: #F56C6C" @click="handleDefinitionDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="block" style="margin-top: 10px;">
            <el-pagination
              v-if="!definitionLoading"
              :current-page="definitionPageCurrent"
              :page-sizes="[50, 100, 200]"
              :page-size="definitionPageSize"
              :total="definitionTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleDefinitionSizeChange"
              @current-change="handleDefinitionCurrentChange" />
          </div>
        </el-tab-pane>

        <el-tab-pane label="特殊工位规则配置维护" name="rule">
          <div class="topDiv">
            <span>类型：</span>
            <el-select v-model="ruleSearch.type" placeholder="全部" filterable clearable size="small" style="width: 180px">
              <el-option v-for="item in definitionTypeOptions" :key="item" :label="item" :value="item" />
            </el-select>
            <span style="margin-left: 10px">工位：</span>
            <el-input v-model="ruleSearch.opName" placeholder="模糊搜索" clearable size="small" style="width: 140px" @keyup.enter.native="handleRuleSearch" />
            <span style="margin-left: 10px">规则键：</span>
            <el-input v-model="ruleSearch.ruleKey" placeholder="模糊搜索" clearable size="small" style="width: 140px" @keyup.enter.native="handleRuleSearch" />
            <span style="margin-left: 10px">启用：</span>
            <el-select v-model="ruleSearch.enable" placeholder="全部" clearable size="small" style="width: 100px">
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
            <el-button type="primary" plain size="small" icon="el-icon-search" style="margin-left: 10px" @click="handleRuleSearch">查询</el-button>
            <el-button type="success" plain size="small" icon="el-icon-plus" @click="handleRuleAdd">新增</el-button>
            <el-button :loading="ruleExportLoading" :disabled="ruleExportLoading" type="warning" plain size="small" icon="el-icon-download" @click="exportRuleExcel">导出</el-button>
          </div>

          <el-table
            v-loading="ruleLoading"
            :data="ruleTableData"
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
            element-loading-text="数据加载中"
            style="width: 100%"
            max-height="650px"
            border
            size="mini">
            <el-table-column align="center" type="index" width="60" label="序号" />
            <el-table-column align="center" prop="id" label="ID" width="80" />
            <el-table-column align="center" prop="type" label="类型" width="190" show-overflow-tooltip />
            <el-table-column align="center" prop="opName" label="工位" width="120" />
            <el-table-column align="center" prop="ruleKey" label="规则键" width="140" show-overflow-tooltip />
            <el-table-column align="center" prop="ruleValue" label="规则值" min-width="180" show-overflow-tooltip />
            <el-table-column align="center" label="启用" width="80">
              <template slot-scope="scope">
                <el-tag :type="scope.row.enable ? 'success' : 'danger'" size="mini">
                  {{ scope.row.enable ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="remark" label="备注" min-width="180" show-overflow-tooltip />
            <el-table-column align="center" label="操作" width="160" fixed="right">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleRuleEdit(scope.row)">编辑</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" style="color: #F56C6C" @click="handleRuleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="block" style="margin-top: 10px;">
            <el-pagination
              v-if="!ruleLoading"
              :current-page="rulePageCurrent"
              :page-sizes="[50, 100, 200]"
              :page-size="rulePageSize"
              :total="ruleTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleRuleSizeChange"
              @current-change="handleRuleCurrentChange" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog :visible.sync="definitionDialogVisible" :title="definitionDialogTitle" center width="520px" :close-on-click-modal="false">
      <el-form ref="definitionForm" :model="definitionForm" :rules="definitionRules" label-position="right" label-width="90px" size="small">
        <el-form-item label="类型:" prop="type">
          <el-input v-model="definitionForm.type" :disabled="definitionDialogType === 'edit'" placeholder="请输入类型" clearable />
        </el-form-item>
        <el-form-item label="工位列表:" prop="opList">
          <el-input v-model="definitionForm.opList" type="textarea" :rows="4" placeholder="多个工位用英文逗号分隔，如 OP100,OP120" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="definitionDialogVisible = false">取消</el-button>
        <el-button type="primary" size="small" :loading="definitionSubmitLoading" @click="submitDefinitionForm">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="ruleDialogVisible" :title="ruleDialogTitle" center width="620px" :close-on-click-modal="false">
      <el-form ref="ruleForm" :model="ruleForm" :rules="ruleRules" label-position="right" label-width="90px" size="small">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="类型:" prop="type">
              <el-select v-model="ruleForm.type" placeholder="请选择类型" filterable allow-create default-first-option style="width: 100%">
                <el-option v-for="item in definitionTypeOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工位:" prop="opName">
              <el-input v-model="ruleForm.opName" placeholder="请输入工位" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规则键:" prop="ruleKey">
              <el-input v-model="ruleForm.ruleKey" placeholder="请输入规则键" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启用:" prop="enable">
              <el-switch v-model="ruleForm.enable" :active-value="1" :inactive-value="0" active-text="启用" inactive-text="禁用" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="规则值:" prop="ruleValue">
          <el-input v-model="ruleForm.ruleValue" placeholder="请输入规则值" clearable />
        </el-form-item>
        <el-form-item label="备注:" prop="remark">
          <el-input v-model="ruleForm.remark" type="textarea" :rows="3" placeholder="请输入备注" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="ruleDialogVisible = false">取消</el-button>
        <el-button type="primary" size="small" :loading="ruleSubmitLoading" @click="submitRuleForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeTab: 'definition',
      definitionLoading: false,
      definitionExportLoading: false,
      definitionSubmitLoading: false,
      definitionTableData: [],
      definitionTypeOptions: [],
      definitionSearch: {
        type: '',
        opList: ''
      },
      definitionTotal: 0,
      definitionPageSize: 50,
      definitionPageCurrent: 1,
      definitionDialogVisible: false,
      definitionDialogType: 'add',
      definitionForm: this.getEmptyDefinitionForm(),
      definitionRules: {
        type: [{ required: true, message: '请输入类型', trigger: 'blur' }]
      },
      ruleLoading: false,
      ruleExportLoading: false,
      ruleSubmitLoading: false,
      ruleTableData: [],
      ruleSearch: {
        type: '',
        opName: '',
        ruleKey: '',
        enable: ''
      },
      ruleTotal: 0,
      rulePageSize: 50,
      rulePageCurrent: 1,
      ruleDialogVisible: false,
      ruleDialogType: 'add',
      ruleForm: this.getEmptyRuleForm(),
      ruleRules: {
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        opName: [{ required: true, message: '请输入工位', trigger: 'blur' }],
        ruleKey: [{ required: true, message: '请输入规则键', trigger: 'blur' }],
        enable: [{ required: true, message: '请选择启用状态', trigger: 'change' }]
      }
    }
  },
  computed: {
    definitionDialogTitle() {
      return this.definitionDialogType === 'add' ? '新增特殊工位定义' : '编辑特殊工位定义'
    },
    ruleDialogTitle() {
      return this.ruleDialogType === 'add' ? '新增特殊工位规则' : '编辑特殊工位规则'
    }
  },
  created() {
    this.getDefinitionData()
    this.getRuleData()
  },
  methods: {
    getEmptyDefinitionForm() {
      return {
        type: '',
        opList: ''
      }
    },
    getEmptyRuleForm() {
      return {
        id: '',
        type: '',
        opName: '',
        ruleKey: '',
        ruleValue: '',
        enable: 1,
        remark: ''
      }
    },
    getDefinitionParam(pageCurrent, pageSize) {
      var param = []
      param[0] = ['类型', this.definitionSearch.type]
      param[1] = ['工位列表', this.definitionSearch.opList]
      param[2] = ['PageCurrent', pageCurrent]
      param[3] = ['PageSize', pageSize]
      param[4] = ['PageCount', '1111', 'int', '1']
      param[5] = ['ItemCount', '1111', 'int', '1']
      return param
    },
    getRuleParam(pageCurrent, pageSize) {
      var param = []
      param[0] = ['类型', this.ruleSearch.type]
      param[1] = ['工位', this.ruleSearch.opName]
      param[2] = ['规则键', this.ruleSearch.ruleKey]
      param[3] = ['启用', this.ruleSearch.enable]
      param[4] = ['PageCurrent', pageCurrent]
      param[5] = ['PageSize', pageSize]
      param[6] = ['PageCount', '1111', 'int', '1']
      param[7] = ['ItemCount', '1111', 'int', '1']
      return param
    },
    getDefinitionData() {
      this.definitionLoading = true
      var Data = this.CreateData('11', '中控参数维护_特殊工位定义_分页查询', this.getDefinitionParam(this.definitionPageCurrent, this.definitionPageSize))
      this.ExecDatabase(Data).then(response => {
        this.definitionTableData = response.data && response.data.result ? response.data.result : []
        this.definitionTotal = response.data && response.data.output && response.data.output[0] ? parseInt(response.data.output[0].ItemCount) || 0 : 0
        this.definitionTypeOptions = this.definitionTableData.map(item => item.type)
        this.definitionLoading = false
      }).catch(error => {
        console.error('查询特殊工位定义失败:', error)
        this.$message.error('查询特殊工位定义失败')
        this.definitionLoading = false
      })
    },
    getRuleData() {
      this.ruleLoading = true
      var Data = this.CreateData('11', '中控参数维护_特殊工位规则_分页查询', this.getRuleParam(this.rulePageCurrent, this.rulePageSize))
      this.ExecDatabase(Data).then(response => {
        this.ruleTableData = response.data && response.data.result ? response.data.result : []
        this.ruleTotal = response.data && response.data.output && response.data.output[0] ? parseInt(response.data.output[0].ItemCount) || 0 : 0
        this.ruleLoading = false
      }).catch(error => {
        console.error('查询特殊工位规则失败:', error)
        this.$message.error('查询特殊工位规则失败')
        this.ruleLoading = false
      })
    },
    handleDefinitionSearch() {
      this.definitionPageCurrent = 1
      this.getDefinitionData()
    },
    handleRuleSearch() {
      this.rulePageCurrent = 1
      this.getRuleData()
    },
    handleDefinitionAdd() {
      this.definitionDialogType = 'add'
      this.definitionForm = this.getEmptyDefinitionForm()
      this.definitionDialogVisible = true
      this.$nextTick(() => {
        this.$refs.definitionForm && this.$refs.definitionForm.clearValidate()
      })
    },
    handleDefinitionEdit(row) {
      this.definitionDialogType = 'edit'
      this.definitionForm = {
        type: row.type,
        opList: row.opList
      }
      this.definitionDialogVisible = true
      this.$nextTick(() => {
        this.$refs.definitionForm && this.$refs.definitionForm.clearValidate()
      })
    },
    handleRuleAdd() {
      this.ruleDialogType = 'add'
      this.ruleForm = this.getEmptyRuleForm()
      this.ruleDialogVisible = true
      this.$nextTick(() => {
        this.$refs.ruleForm && this.$refs.ruleForm.clearValidate()
      })
    },
    handleRuleEdit(row) {
      this.ruleDialogType = 'edit'
      this.ruleForm = {
        id: row.id,
        type: row.type,
        opName: row.opName,
        ruleKey: row.ruleKey,
        ruleValue: row.ruleValue,
        enable: row.enable ? 1 : 0,
        remark: row.remark
      }
      this.ruleDialogVisible = true
      this.$nextTick(() => {
        this.$refs.ruleForm && this.$refs.ruleForm.clearValidate()
      })
    },
    submitDefinitionForm() {
      this.$refs.definitionForm.validate(valid => {
        if (!valid) return
        this.definitionSubmitLoading = true
        var param = []
        param[0] = ['类型', this.definitionForm.type]
        param[1] = ['工位列表', this.definitionForm.opList]
        var procedureName = this.definitionDialogType === 'add' ? '中控参数维护_特殊工位定义_增加' : '中控参数维护_特殊工位定义_编辑'
        var Data = this.CreateData('11', procedureName, param)
        this.ExecDatabase(Data).then(response => {
          this.handleSubmitResult(response, () => {
            this.definitionDialogVisible = false
            this.getDefinitionData()
          })
          this.definitionSubmitLoading = false
        }).catch(error => {
          console.error('保存特殊工位定义失败:', error)
          this.$message.error('保存特殊工位定义失败')
          this.definitionSubmitLoading = false
        })
      })
    },
    submitRuleForm() {
      this.$refs.ruleForm.validate(valid => {
        if (!valid) return
        this.ruleSubmitLoading = true
        var param = []
        param[0] = ['ID', this.ruleForm.id]
        param[1] = ['类型', this.ruleForm.type]
        param[2] = ['工位', this.ruleForm.opName]
        param[3] = ['规则键', this.ruleForm.ruleKey]
        param[4] = ['规则值', this.ruleForm.ruleValue]
        param[5] = ['启用', this.ruleForm.enable]
        param[6] = ['备注', this.ruleForm.remark]
        var procedureName = this.ruleDialogType === 'add' ? '中控参数维护_特殊工位规则_增加' : '中控参数维护_特殊工位规则_编辑'
        var Data = this.CreateData('11', procedureName, param)
        this.ExecDatabase(Data).then(response => {
          this.handleSubmitResult(response, () => {
            this.ruleDialogVisible = false
            this.getRuleData()
          })
          this.ruleSubmitLoading = false
        }).catch(error => {
          console.error('保存特殊工位规则失败:', error)
          this.$message.error('保存特殊工位规则失败')
          this.ruleSubmitLoading = false
        })
      })
    },
    handleDefinitionDelete(row) {
      this.$confirm('确认删除该特殊工位定义吗？', '提示', { type: 'warning' }).then(() => {
        var param = []
        param[0] = ['类型', row.type]
        var Data = this.CreateData('11', '中控参数维护_特殊工位定义_删除', param)
        this.ExecDatabase(Data).then(response => {
          this.handleSubmitResult(response, () => {
            this.getDefinitionData()
          })
        })
      }).catch(() => {})
    },
    handleRuleDelete(row) {
      this.$confirm('确认删除该特殊工位规则吗？', '提示', { type: 'warning' }).then(() => {
        var param = []
        param[0] = ['ID', row.id]
        var Data = this.CreateData('11', '中控参数维护_特殊工位规则_删除', param)
        this.ExecDatabase(Data).then(response => {
          this.handleSubmitResult(response, () => {
            this.getRuleData()
          })
        })
      }).catch(() => {})
    },
    handleSubmitResult(response, callback) {
      var result = response.data && response.data[0] ? response.data[0] : {}
      if (result.result === 1) {
        this.$message.success(result.msg || '操作成功')
        callback && callback()
      } else {
        this.$message.error(result.msg || '操作失败')
      }
    },
    exportDefinitionExcel() {
      if (this.definitionTableData.length === 0) {
        this.$message.warning('暂无数据')
        return
      }
      var exportData = JSON.parse(this.CreateData('2005', '中控参数维护_特殊工位定义_分页查询', this.getDefinitionParam(1, 99999999)))
      exportData.exportFileName = '特殊工位定义维护'
      exportData.exportColumns = 'type=类型,opList=工位列表'
      this.runExcelExport(JSON.stringify(exportData), 'definitionExportLoading')
    },
    exportRuleExcel() {
      if (this.ruleTableData.length === 0) {
        this.$message.warning('暂无数据')
        return
      }
      var exportData = JSON.parse(this.CreateData('2005', '中控参数维护_特殊工位规则_分页查询', this.getRuleParam(1, 99999999)))
      exportData.exportFileName = '特殊工位规则配置维护'
      exportData.exportColumns = 'id=ID,type=类型,opName=工位,ruleKey=规则键,ruleValue=规则值,enable=启用,remark=备注'
      this.runExcelExport(JSON.stringify(exportData), 'ruleExportLoading')
    },
    handleDefinitionSizeChange(val) {
      this.definitionPageCurrent = 1
      this.definitionPageSize = val
      this.getDefinitionData()
    },
    handleDefinitionCurrentChange(val) {
      this.definitionPageCurrent = val
      this.getDefinitionData()
    },
    handleRuleSizeChange(val) {
      this.rulePageCurrent = 1
      this.rulePageSize = val
      this.getRuleData()
    },
    handleRuleCurrentChange(val) {
      this.rulePageCurrent = val
      this.getRuleData()
    }
  }
}
</script>

<style scoped>
.topCard {
  margin: 5px;
}

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