<script setup>
import { CirclePlus } from '@element-plus/icons-vue'

import { getWorkFlowList, getAllWaterFactoryList, getPositionList, getAssayList, putWorkFlow, postWorkFlow, delWorkFlow } from '@/api/configuration'
import { getAllDeviceList} from '@/api/client/manage'

const { proxy } = getCurrentInstance();

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
});

const total = ref(0);
const loading = ref(false);
const tableData = ref([]);

const waterFactoryOptions = ref([]);
const deviceOptions = ref([]);
const pointOptions = ref([]);
const assayOptions = ref([]);

const formData = ref({});
const formRef = ref(null);

const dialogVisible = ref(false);
const rules = {
  name: { required: true, message: '请输入化验流程名称', trigger: 'blur' },
  organizationId: { required: true, message: '请选择所属水厂', trigger: 'blur' },
  code: { required: true, message: '请输入化验流程编号', trigger: 'blur' },
  deviceId: { required: true, message: '请选择所属设备', trigger: 'blur' },
  totalSteps: { required: true, message: '化验总步数', trigger: 'blur' },
  items: { type: 'array', required: true, message: '请添加化验内容', trigger: 'blur' }
}

const initPageData = async () => {
  loading.value = true;

  const { total: tableTotal, rows } = await getWorkFlowList(queryParams.value);

  tableData.value = rows.map(val => ({
    ...val,
    items: val.items.map(item => ({
      ...item,
      itemId: item.id,
      itemName: item.assayItem?.name,
      positionId: item.position?.id,
      positionName: item.position?.name,
      workflowId: val.id
    }))
  }));

  total.value = tableTotal;
  loading.value = false;
}


// 查询
const handleQuery = async() => {
  initPageData();
}

// 重置
const handleReset = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10
  }
  initPageData();
}

// 编辑流程
const handleTableEdit = (row) => {
  formData.value = { ...row };
  dialogVisible.value = true;
}

// Dialog - 新增 or 修改 化验流程
const handleDialogConfirm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async(valid, fields) => {
    if (valid) {
      formData.value.id ? await putWorkFlow(formData.value) : await postWorkFlow(formData.value);
      formRef.value.resetFields();
      dialogVisible.value = false;
      proxy.$modal.msgSuccess("操作成功");
      initPageData();
    } else {
      console.log('error submit!', fields)
    }
  })
}

// Dialog - 重置表单
const handleDialogReset = () => {
  formData.value = {};
  formRef.value.resetFields();
}

// Dialog - 新增行
const handleAddRow = () => {
  const { itemId, positionId, id: workflowId } = formData.value;
  if ( !itemId ) {
    return proxy.$modal.msgError("请先选择化验项目");
  }
  if ( !positionId ) {
    return proxy.$modal.msgError("请先选择取样点位");
  }
  formRef.value.validate("items");
  const params = {
    itemId,
    itemName: assayOptions.value.find(({ id }) => id === itemId).name,
    positionId,
    positionName: pointOptions.value.find(({ id }) => id === positionId).name,
    workflowId
  }
  if ( !formData.value.items?.length ) formData.value.items = [];
  formData.value.items.push(params);
}

// Table - 删除
const handleDelete = async ({ id }) => {
  await delWorkFlow(id);
  proxy.$modal.msgSuccess("删除成功");
  initPageData();
}


// Tag - 删除行
const handleCloseTag = (index) => {
  formData.value.items.splice(index, 1);
}

onMounted(async () => {
  // 水厂
  getAllWaterFactoryList().then(({ data }) => waterFactoryOptions.value = data)
  // 设备
  getAllDeviceList().then(({ data }) => deviceOptions.value = data)
  // 化验项目
  getAssayList({ pageNum: 1, pageSize: 9999 }).then(({ rows }) => assayOptions.value = rows)
  // 点位
  getPositionList({ pageNum: 1, pageSize: 10000 }).then(({ rows }) => pointOptions.value = rows)
  // 初始化数据
  initPageData();
})
</script>

<template>
  <section>
    <el-card shadow="never" :body-style="{ border: '0px' }" style="margin-bottom: 10px;">
      <template #header>
        <p class="space-x-[10px]">
          <span class="font-bold">数据筛选</span>
        </p>
      </template>
      <el-row class="pt-[5px]" justify="space-between" :gutter="20">
        <el-col :span="6">
          <el-form-item label="水厂名称">
            <el-select v-model="queryParams.organizationId" placeholder="请选择水厂名称" filterable clearable>
              <el-option v-for="item in waterFactoryOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="设备SN / 名称">
            <el-select v-model="queryParams.deviceId" placeholder="请选择设备SN" filterable clearable>
              <el-option v-for="item in deviceOptions" :key="item.deviceId" :label="(item.deviceSn ? item.deviceSn + '-' : '') + item.deviceName  || ''" :value="item.deviceId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="化验流程名称">
            <el-input v-model.trim="queryParams.name" placeholder="请输入化验流程名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="化验流程编号">
            <el-input v-model.trim="queryParams.code" placeholder="请输入化验流程编号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="18">
          <div class="flex justify-end">
            <el-button type="primary" @click="handleQuery" :loading="loading">查询</el-button>
            <el-button @click="handleReset" :loading="loading">重置</el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-card shadow="never" :body-style="{ padding: '20px' }">
      <div class="flex justify-between items-center mb-[10px]">
        <el-button type="primary" @click="dialogVisible = true" :loading="loading" :icon="CirclePlus">新增化验流程</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%" v-loading="loading" row-key="id">
        <el-table-column prop="code" label="化验流程编号" width="180" fixed/>
        <el-table-column prop="name" label="化验流程名称" width="180" />
        <el-table-column prop="organization.name" label="所属水厂名称" width="180"/>
        <el-table-column prop="bizDevice.deviceSn" label="所属设备SN" width="180"/>
        <el-table-column prop="bizDevice.deviceName" label="所属设备名称" width="180"/>
        <el-table-column prop="xxxxxxxx" label="化验项目" width="400" show-overflow-tooltip>
          <template #default="{row}">
            <div class="space-x-[4px]">
              <el-tag v-for="item in row.items" :key="item.id">{{item?.assayItem?.name}}（{{ item?.position?.name }}）</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="totalSteps" label="化验总步数" width="180"/>
        <el-table-column prop="createUser.nickName" label="创建人" width="180"/>
        <el-table-column prop="createTime" label="创建时间" width="180"/>
        <el-table-column prop="address" label="操作" fixed="right" width="100">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleTableEdit(row)">编辑</el-button>
            <el-popconfirm title="请确认是否删除?" @confirm="handleDelete(row)" width="200">
              <template #reference>
                <el-button link type="primary" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

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

    <el-dialog v-model="dialogVisible" :title="formData.id ? '编辑化验流程' : '新增化验流程'" width="900" @closed="handleDialogReset">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="110px" label-position="left" require-asterisk-position="right">
        <el-row justify="space-between">
          <el-col :span="11">
            <el-form-item label="化验流程名称" prop="name">
              <el-input v-model.trim="formData.name" placeholder="请输入流程名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="所属水厂" prop="organizationId">
              <el-select v-model="formData.organizationId" placeholder="请选择所属水厂" filterable clearable>
                <el-option v-for="item in waterFactoryOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="化验流程编号" prop="code">
              <el-input v-model.trim="formData.code" placeholder="请输入化验流程编号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="所属设备" prop="deviceId">
              <el-select v-model="formData.deviceId" placeholder="请选所属设备" filterable clearable>
                <el-option v-for="item in deviceOptions" :key="item.deviceId" :label="item.deviceName" :value="item.deviceId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="化验总步数" prop="totalSteps">
              <el-input v-model.trim="formData.totalSteps" placeholder="请输入总步数" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider border-style="dashed" />

        <el-form-item label="化验内容" prop="items">
          <el-row class="w-full" :gutter="20">
            <el-col :span="8">
              <el-select v-model="formData.itemId" placeholder="请选择化验项目" filterable clearable>
                <el-option v-for="item in assayOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-select v-model="formData.positionId" placeholder="请选择取样点位" filterable clearable>
                <el-option v-for="item in pointOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-col>
            <el-col :span="8">
              <el-button type="primary" @click="handleAddRow(row)">添加</el-button>
            </el-col>
          </el-row>
          <div class="w-full min-h-[100px] px-[10px] py-[10px] mt-[30px] bg-[#f3f5f9] space-x-[10px]">
            <el-tag v-for="item, index in formData.items" :key="index" closable type="primary" @close="handleCloseTag(index)">
              <span>{{ item.itemName }}（{{ item.positionName }}）</span>
            </el-tag>
          </div>
        </el-form-item>
        
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" >取 消</el-button>
          <el-button @click="handleDialogConfirm" type="primary">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    
  </section>
</template>

<style lang="scss" scoped>

</style>