<template>
  <div class="app-container">
    <TableSearch
        :queryParams="queryParams"
        :showSearch="showSearch"
        label-width="90px"
        queryRef="queryRef"
        @refresh="resetQuery"
        @search="handleQuery"
    >
      <template #one>
        <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
          <el-form-item label="检测项名称" prop="paramEnName">
            <el-input
                v-model="queryParams.paramEnName"
                clearable
                placeholder="请输入检测项名称"
                @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
      </template>
    </TableSearch>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['test:params:add']"
            icon="Plus"
            plain
            type="primary"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['test:params:edit']"
            :disabled="single"
            icon="Edit"
            plain
            type="success"
            @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['test:params:remove']"
            :disabled="multiple"
            icon="Delete"
            plain
            type="danger"
            @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['test:params:export']"
            icon="Download"
            plain
            type="warning"
            @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="paramsList" row-key="id" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column align="center" label="检测项" prop="detectName"/>
      <el-table-column align="center" label="操作顺序" prop="sort"/>
      <el-table-column align="center" label="操作类型" prop="operationType">
        <template #default="scope">
          <TableTags :options="paramsListData.typeList" :value="scope.row.operationType"></TableTags>
        </template>
      </el-table-column>
      <el-table-column align="center" label="参数名" prop="paramCnName" required/>
      <el-table-column align="center" label="参数源" prop="paramSource">
        <template #default="scope">
          <TableTags :options="paramsListData.sourceList" :value="scope.row.paramSource"></TableTags>
        </template>
      </el-table-column>
      <el-table-column align="center" show-overflow-tooltip label="参数值" prop="sourceValue"/>
      <el-table-column align="center" label="是否必填" prop="required">
        <template #default="scope">
          <TableTags :options="[
               {
                label: '是',
                value: true,
                type: 'success'
              },
              {
                label: '否',
                value: false,
                type: 'danger'
              }
          ]" :value="scope.row.required">
          </TableTags>
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" prop="remark"/>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="150">
        <template #default="scope">
          <el-button v-hasPermi="['test:params:edit']" icon="Edit" link type="primary" @click="handleUpdate(scope.row)">
            修改
          </el-button>
          <el-button v-hasPermi="['test:params:remove']" icon="Delete" link type="primary"
                     @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        :total="total"
        @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="680px">
      <el-form ref="paramsRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="检测项" prop="detectId">
              <el-select v-model="form.detectId" placeholder="请选择检测项">
                <el-option v-for="item in paramsListData.detectList" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作顺序" prop="sort">
              <el-input-number v-model="form.sort" :min="1" style="width: 100%;"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="参数英文名" prop="paramEnName">
              <el-input v-model="form.paramEnName" placeholder="请输入参数名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="参数中文名" prop="paramCnName">
              <el-input v-model="form.paramCnName" placeholder="请输入参数名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="操作类型" prop="operationType">
              <el-select v-model="form.operationType" placeholder="请选择操作类型">
                <el-option v-for="item in paramsListData.typeList" :key="item.value" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="参数来源" prop="paramSource">
              <el-radio-group v-model="form.paramSource" placeholder="请输入参数来源"
                              @change="()=>form.sourceValue=null">
                <el-radio-button v-for="item in paramsListData.sourceList" :key="item.value" :label="item.label"
                                 :value="item.value"/>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <!--        TEXT 用户输入文本-->
            <!--        STATIC 静态默认值-->
            <!--        DICT 字典数据-->
            <!--        API 接口获取-->
            <el-form-item label="来源值" prop="sourceValue">
              <template v-if="form.paramSource === 'TEXT'">
                <el-input v-model="form.sourceValue" :rows="3" placeholder="请输入文本" type="textarea"/>
              </template>
              <template v-if="form.paramSource === 'STATIC'">
                <el-input v-model="form.sourceValue" :rows="3" placeholder="请输入静态默认值" type="textarea"/>
              </template>
              <template v-if="form.paramSource === 'DICT'">
                <!--                <el-select v-model="form.sourceValue" placeholder="请输入字典数据">-->
                <!--                  <el-option v-for="item in paramsListData.typeList" :key="item.value" :label="item.label" :value="item.value"></el-option>-->
                <!--                </el-select>-->
                <el-input v-model="form.sourceValue" :rows="3" placeholder="请输入静态默认值" type="textarea"/>
              </template>
              <template v-if="form.paramSource === 'API'">
                <!--                <el-select v-model="form.sourceValue" placeholder="请选择接口数据">-->
                <!--                  <el-option v-for="item in paramsListData.typeList" :key="item.value" :label="item.label" :value="item.value"></el-option>-->
                <!--                </el-select>-->
                <el-input v-model="form.sourceValue" :rows="3" placeholder="请输入静态默认值" type="textarea"/>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否必填" prop="required">
              <el-radio-group v-model="form.required">
                <el-radio :value="true" size="large">是</el-radio>
                <el-radio :value="false" size="large">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" :rows="3" placeholder="请输入内容" type="textarea"/>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script name="Params" setup>
import {
  addParams,
  delParams,
  getParams,
  getParamSources,
  getParamTypes,
  listParams,
  updateParams
} from "@/api/test/params"
import {listDetect} from "@/api/test/detect.js";
import TableSearch from "@/components/TableSearch/index.vue"
import TableTags from "@/components/TableTags/index.vue";
import { onMounted } from "vue";

const {proxy} = getCurrentInstance()

const paramsList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    detectId: null,
    operationType: null,
    sort: null,
    paramEnName: null,
    paramCnName: null,
    paramSource: null,
    sourceValue: null,
    required: null,
  },
  rules: {
    detectId: [
      {required: true, message: "检测项ID不能为空", trigger: "blur"}
    ],
    operationType: [
      {required: true, message: "操作类型不能为空", trigger: "change"}
    ],
    paramEnName: [
      {required: true, message: "参数名称不能为空", trigger: "blur"}
    ],
    paramCnName: [
      {required: true, message: "参数名称不能为空", trigger: "blur"}
    ],
    paramSource: [
      {required: true, message: "参数来源不能为空", trigger: "blur"}
    ],
  }
})

const {queryParams, form, rules} = toRefs(data)

/** 查询参数配置列表 */
function getList() {
  loading.value = true
  listParams(queryParams.value).then(response => {
    paramsList.value = response.data?.sort((a, b) => {
      // 先比较 detectName
      if (a.itemName < b.itemName) return -1;
      if (a.itemName > b.itemName) return 1;
      // 如果 detectName 相同，则比较 sort
      return a.sort - b.sort;
    })
    total.value = paramsList.value.length || 0
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    detectId: null,
    operationType: null,
    sort: 1,
    paramEnName: null,
    paramCnName: null,
    paramSource: "TEXT",
    sourceValue: null,
    required: false,
    remark: null
  }
  proxy.resetForm("paramsRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  console.log(queryParams.value,'111')
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加参数配置"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getParams(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改参数配置"
  })
}

/** 提交按钮 */
function submitForm() {
  console.log(form.value, '11')
  proxy.$refs["paramsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateParams(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addParams(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除参数配置编号为"' + _ids + '"的数据项？').then(function () {
    return delParams(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {
  })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('test/params/export', {
    ...queryParams.value
  }, `params_${new Date().getTime()}.xlsx`)
}

const paramsListData = reactive({
  sourceList: [],
  typeList: [],
  detectList: [],
})

const getParamSourcesList = (row) => {
  getParamSources().then((response) => {
    paramsListData.sourceList = response.data?.map(item => ({label: item.description, value: item.code}))
  })
}
const getParamTypesList = (row) => {
  getParamTypes().then((response) => {
    paramsListData.typeList = response.data?.map(item => ({label: item.description, value: item.code}))
  })
}
const getDetectList = (row) => {
  listDetect().then((response) => {
    paramsListData.detectList = response.rows?.map(item => ({label: item.detectName, value: item.id}))
  })
}

onMounted(() => {
  getList()
  getParamSourcesList()
  getParamTypesList()
  getDetectList()
})
</script>
