<template>
  <div class="app-container">
    <el-row :gutter="2">
      <el-col :span="6">
        <el-card>
          <div slot="header">
            <span>阀值来源信息</span>
            <el-button
              type="primary"
              size="small"
              style="margin-left: 8px"
              @click="handleAdd"
            >新增</el-button>
          </div>
          <el-table
            v-loading="listLoading"
            :data="sourceData.results"
            style="width: 100%;margin-top:10px;"
            border
            stripe
            fit
            highlight-current-row
            max-height="600"
            @row-click="sourceRowClick"
          >
            <el-table-column type="index" width="50" />
            <el-table-column align="center" label="来源名称" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.name }}</template>
            </el-table-column>
            <el-table-column align="center" label="作者" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.author }}</template>
            </el-table-column>
            <el-table-column align="center" label="发表年份">
              <template slot-scope="scope">{{ scope.row.publish_year }}</template>
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="small"
                  icon="el-icon-edit"
                  :disabled="!checkPermission(['source_update'])"
                  @click="handleEdit(scope)"
                />
                <el-button
                  type="danger"
                  size="small"
                  icon="el-icon-delete"
                  :disabled="!checkPermission(['source_delete'])"
                  @click="handleDelete(scope)"
                />
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.limit"
            @pagination="getList"
          />
          <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑阀值来源信息':'新增阀值来源信息'">
            <el-form
              ref="commonForm"
              :model="source"
              label-width="80px"
              label-position="right"
              :rules="rule1"
            >
              <el-form-item label="来源名称" prop="name">
                <el-input v-model="source.name" placeholder="名称" />
              </el-form-item>
              <el-form-item label="作者" prop="author">
                <el-input v-model="source.author" placeholder="作者" />
              </el-form-item>
              <el-form-item label="发表年份" prop="publish_year">
                <el-input v-model.number="source.publish_year" placeholder="发表年份" />
              </el-form-item>
              <el-form-item label="备注" prop="note">
                <el-input v-model="source.note" placeholder="备注" />
              </el-form-item>
            </el-form>
            <div style="text-align:right;">
              <el-button type="danger" @click="dialogVisible=false">取消</el-button>
              <el-button type="primary" @click="confirm('commonForm')">确认</el-button>
            </div>
          </el-dialog>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card>
          <div slot="header">
            <span>阀值信息</span>
            <el-button
              type="primary"
              size="small"
              style="margin-left: 8px"
              @click="AddThreshold"
            >新增</el-button>
          </div>
          <el-table
            v-loading="listLoading"
            :data="thresholdData.results"
            style="width: 100%;margin-top:10px;"
            border
            stripe
            fit
            highlight-current-row
            max-height="600"
          >
            <el-table-column type="index" :index="hindex" width="50" />
            <el-table-column align="center" label="阀值来源" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.source_.name }}</template>
            </el-table-column>
            <el-table-column align="center" label="化合物分类" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.compound_cate }}</template>
            </el-table-column>
            <el-table-column align="center" label="气味类型" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.odor_type }}</template>
            </el-table-column>
            <el-table-column align="center" label="阈值类型" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.threshold_type }}</template>
            </el-table-column>
            <el-table-column align="center" label="毒性类型" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.toxicity_type }}</template>
            </el-table-column>
            <el-table-column align="center" label="中文名" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.chinese_name }}</template>
            </el-table-column>
            <el-table-column align="center" label="ppm" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.ppm }}</template>
            </el-table-column>
            <el-table-column align="center" label="ppm符号标记" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.ppm_sign }}</template>
            </el-table-column>
            <el-table-column align="center" label="质量浓度" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.mass }}</template>
            </el-table-column>
            <el-table-column align="center" label="毒性" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.toxicity }}</template>
            </el-table-column>
            <el-table-column align="center" label="质量浓度符号标记" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.mass_sign }}</template>
            </el-table-column>
            <el-table-column align="center" label="分子质量" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.molecular }}</template>
            </el-table-column>
            <el-table-column align="center" label="cas号" show-overflow-tooltip>
              <template slot-scope="scope">{{ scope.row.cas }}</template>
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="small"
                  icon="el-icon-edit"
                  :disabled="!checkPermission(['threshold_update'])"
                  @click="ThresholdEdit(scope)"
                />
                <el-button
                  type="danger"
                  size="small"
                  icon="el-icon-delete"
                  :disabled="!checkPermission(['threshold_delete'])"
                  @click="DeleteThreshold(scope)"
                />
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="thresholdData.count>0"
            :total="thresholdData.count"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.limit"
            @pagination="getThresholdList"
          />
          <el-dialog :visible.sync="dialogVisibleT" :title="dialogType2==='edit'?'编辑阀值信息':'新增阀值信息'">
            <el-form
              ref="commonForm2"
              :model="threshold"
              label-width="140px"
              label-position="right"
              :rules="rule2"
            >
              <el-row>
                <el-col :span="12">
                  <el-form-item label="阀值来源" prop="source">
                    <el-select v-model="threshold.source" placeholder="请选择阀值来源">
                      <el-option
                        v-for="item in optionsSource"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="化合物分类" prop="compound_cate">
                    <el-input v-model="threshold.compound_cate" placeholder="化合物分类" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="气味类型" prop="odor_type">
                    <el-input v-model="threshold.odor_type" placeholder="气味类型" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="阀值类型" prop="threshold_type">
                    <el-input v-model="threshold.threshold_type" placeholder="阀值类型" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="毒性类型" prop="toxicity_type">
                    <el-input v-model="threshold.toxicity_type" placeholder="毒性类型" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="中文名" prop="chinese_name">
                    <el-input v-model="threshold.chinese_name" placeholder="中文名" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="ppm"
                    prop="ppm"
                    :rules="[
                      { required: true, message: 'ppm不能为空'},
                      { type: 'number', message: 'ppm必须为数字值'}
                    ]"
                  >
                    <el-input v-model.number="threshold.ppm" placeholder="ppm" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="ppm符号标记" prop="ppm_sign">
                    <el-input v-model="threshold.ppm_sign" placeholder="ppm符号标记" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="质量浓度"
                    prop="mass"
                    :rules="[
                      { required: true, message: '质量浓度不能为空'},
                      { type: 'number', message: '质量浓度必须为数字值'}
                    ]"
                  >
                    <el-input v-model.number="threshold.mass" placeholder="质量浓度" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">

                  <el-form-item
                    label="毒性"
                    prop="toxicity"
                    :rules="[
                      { required: true, message: '毒性不能为空'},
                      { type: 'number', message: '毒性必须为数字值'}
                    ]"
                  >
                    <el-input v-model.number="threshold.toxicity" placeholder="毒性" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="质量浓度符号标记" prop="mass_sign">
                    <el-input v-model="threshold.mass_sign" placeholder="质量浓度符号标记" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">

                  <el-form-item
                    label="分子质量"
                    prop="molecular"
                    :rules="[
                      { required: true, message: '分子质量不能为空'},
                      { type: 'number', message: '分子质量必须为数字值'}
                    ]"
                  >
                    <el-input v-model.number="threshold.molecular" placeholder="分子质量" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="cas号" prop="cas">
                    <el-input v-model="threshold.cas" placeholder="cas号" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div style="text-align:right;">
              <el-button type="danger" @click="dialogVisibleT=false">取消</el-button>
              <el-button type="primary" @click="confirmThreshold('commonForm2')">确认</el-button>
            </div>
          </el-dialog>
        </el-card>
      </el-col>
    </el-row></div>
</template>

<script>
import { getSourceList, createSource, deleteSource, updateSource, getThresholdList,
  createThreshold, deleteThreshold, updateThreshold } from '@/api/cms'
import checkPermission from '@/utils/permission'
import { genTree, deepClone } from '@/utils'
import Pagination from '@/components/Pagination'

const listQuery = {
  page: 1,
  limit: 20,
  search: ''
}
// 阀值来源
const defaultObj = {
  id: '',
  name: '',
  author: '',
  publish_year: null,
  note: ''
}
// 阀值
const defaultObjT = {
  source: null,
  compound_cate: '',
  odor_type: '',
  threshold_type: '',
  toxicity_type: '',
  chinese_name: '',
  ppm: null,
  ppm_sign: '',
  mass: null,
  toxicity: '',
  mass_sign: '',
  molecular: '',
  cas: ''
}
export default {
  components: { Pagination },
  data() {
    var check_publish_year = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('发表年份不能为空'))
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (value < 0 && value > 32767) {
            callback(new Error('必须0到32767之前的数值'))
          } else {
            callback()
          }
        }
      }, 1000)
    }
    return {
      listQuery: Object.assign({}, listQuery),
      source: defaultObj,
      threshold: defaultObjT,
      search: '',
      sourceData: [],
      thresholdData: [],
      optionsSource: [],
      listLoading: true,
      dialogVisible: false,
      dialogVisibleT: false,
      dialogType: 'new',
      dialogType2: 'new',
      rule1: {
        name: [{ required: true, message: '请输入来源名称', trigger: 'blur' }],
        publish_year: [
          { validator: check_publish_year, trigger: 'blur' }
        ]
      },
      rule2: {
        source: [{ required: true, message: '请选择来源名称', trigger: 'change' }],
        compound_cate: [{ required: true, message: '请输入化合物分类', trigger: 'blur' }],
        chinese_name: [{ required: true, message: '请输入中文名', trigger: 'blur' }],
        ppm_sign: [{ required: true, message: '请输入ppm符号标记', trigger: 'blur' }],
        mass_sign: [{ required: true, message: '请输入质量浓度符号标记', trigger: 'blur' }],
        cas: [{ required: true, message: '请输入cas号', trigger: 'blur' }]
      }

    }
  },
  created() {
    this.getList()
    this.getThresholdList()

    this.getSourceAll()
  },
  methods: {
    checkPermission,
    // 表格序号顺延
    hindex(index) {
      return (this.listQuery.page - 1) * this.listQuery.limit + index + 1
    },
    // 阀值来源列表
    getList() {
      this.listLoading = true
      getSourceList().then(response => {
        this.sourceData = response.data
        this.listLoading = false
      })
    },
    // 阀值来源行点击
    sourceRowClick(row) {
      this.listQuery.source = row.id
      this.threshold.source = row.id
      this.getThresholdList()
    },
    resetFilter() {
      this.listQuery = {
        page: 1,
        limit: 20,
        search: ''
      }
      this.getList()
    },
    // 阀值来源添加
    handleAdd() {
      this.source = Object.assign({}, defaultObj)
      this.dialogType = 'new'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['commonForm'].clearValidate()
      })
    },
    // 阀值来源编辑
    handleEdit(scope) {
      this.source = Object.assign({}, scope.row) // copy obj
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['commonForm'].clearValidate()
      })
    },
    // 阀值来源删除
    handleDelete(scope) {
      this.$confirm('确认删除该阀值来源数据吗?将丢失数据!', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'error'
      })
        .then(async() => {
          await deleteSource(scope.row.id)
          this.getList()
          this.$message({
            type: 'success',
            message: '成功删除!'
          })
        })
        // eslint-disable-next-line handle-callback-err
        .catch(err => {
          // console.error(err);
        })
    },
    // 添加、编辑from表单提交
    async confirm(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          const isEdit = this.dialogType === 'edit'
          if (isEdit) {
            updateSource(this.source.id, this.source).then(
              () => {
                this.getList()
                this.dialogVisible = false
                this.$message.success('成功')
              }
            )
          } else {
            createSource(this.source).then(res => {
              this.getList()
              this.dialogVisible = false
              this.$message.success('成功')
            })
          }
        } else {
          return false
        }
      })
    },
    // 阀值来源下拉列表
    getSourceAll() {
      getSourceList().then((response) => {
        this.optionsSource = genTree(response.data.results)
      })
    },
    // 阀值信息列表
    getThresholdList() {
      this.listLoading = true
      getThresholdList(this.listQuery).then(response => {
        this.thresholdData = response.data
        this.listLoading = false
      })
    },
    // 阀值添加
    AddThreshold() {
      this.threshold = Object.assign({}, defaultObjT)
      this.dialogType2 = 'new'
      this.dialogVisibleT = true
      this.$nextTick(() => {
        this.$refs['commonForm2'].clearValidate()
      })
    },
    // 阀值编辑
    ThresholdEdit(scope) {
      this.threshold = Object.assign({}, scope.row) // copy obj
      this.dialogType2 = 'edit'
      this.dialogVisibleT = true
      this.$nextTick(() => {
        this.$refs['commonForm2'].clearValidate()
      })
    },
    // 阀值删除
    DeleteThreshold(scope) {
      this.$confirm('确认删除该阀值数据吗?将丢失数据!', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'error'
      })
        .then(async() => {
          await deleteThreshold(scope.row.id)
          this.getThresholdList()
          this.$message({
            type: 'success',
            message: '成功删除!'
          })
        })
        // eslint-disable-next-line handle-callback-err
        .catch(err => {
          // console.error(err);
        })
    },
    // 添加、编辑from表单提交
    async confirmThreshold(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          const isEdit = this.dialogType2 === 'edit'
          if (isEdit) {
            updateThreshold(this.threshold.id, this.threshold).then(
              () => {
                this.getThresholdList()
                this.dialogVisibleT = false
                this.$message.success('成功')
              }
            )
          } else {
            createThreshold(this.threshold).then(res => {
              this.getThresholdList()
              this.dialogVisibleT = false
              this.$message.success('成功')
            })
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
