<script setup>
  import { reactive, ref } from 'vue'
  // import { FormInstance } from 'element-plus'
  import axios from 'axios';
  import { ElMessage } from 'element-plus'
  import {addSNsApi, getSNsApi, deleteSNsApi, getSNsByConditionApi , listProjectSelectApi} from '../api/api';

  const addFormRef = ref()
  const deleteFormRef = ref()
  const conditionFormRef = ref()

  //获取的SN内容
  const SNsContent = ref('')

  //当前显示的表单 1-添加SN 2-获取SN 3-删除SN
  const currForm = ref('1');

  // 条件查询表单
  const conditionForm = reactive({
    projectName: '',
    sns: ''
  })

  const changeForm = (tab, event) => {
    currForm.value = tab.props.name;
    if (currForm.value === '3') {
      fetchProjectOptions()
    }
    // //把SN数据查出来
    // if (currForm.value == 3) {
    //   axios({
    //       method: getSNsApi.method,
    //       url: getSNsApi.url
    //   }).then(response => {
    //       if (response.data.code == 200) {
    //         SNsContent.value = response.data.data;
    //
    //       } else {
    //           ElMessage({
    //               message: response.data.message,
    //               type: 'error',
    //           })
    //       }
    //
    //   }).catch(err => {
    //       ElMessage.error(err)
    //   })
    // }
    //
  }

  // 项目名称下拉选项
  const projectOptions = ref([])
  const loadingProjects = ref(false)

  // 获取项目名称下拉列表
  const fetchProjectOptions = async () => {
    try {
      loadingProjects.value = true
      const response = await axios({
        method: listProjectSelectApi.method,
        url: listProjectSelectApi.url
      })
      if (response.data.code === 200) {
        projectOptions.value = response.data.data || []
      }
    } catch (err) {
      ElMessage.error('获取项目列表失败')
    } finally {
      loadingProjects.value = false
    }
  }


  // 提交条件查询
  const submitConditionForm = async (formInstance) => {
    if (!formInstance) return

    try {
      await formInstance.validate()
      const response = await axios({
        method: getSNsByConditionApi.method,
        url: getSNsByConditionApi.url,
        data: {
          projectName: conditionForm.projectName,
          sns: conditionForm.sns
        }
      })

      if (response.data.code === 200) {
        SNsContent.value = response.data.data
        ElMessage.success('查询成功')
      } else {
        ElMessage.error(response.data.message || '查询失败')
      }
    } catch (err) {
      if (err.name !== 'Error') { // 不是表单验证错误
        ElMessage.error(err.message || '查询异常')
      }
    }
  }

  // 重置条件表单
  const resetConditionForm = (formInstance) => {
    if (!formInstance) return
    formInstance.resetFields()
    SNsContent.value = '...'
  }


  //添加SN的表单
  const dynamicValidateAddForm = reactive({
    SNs: [
      {
        key: 1,
        value: '',
      },
    ],
    projectName: '',
  })

  //删除SN的表单
  const dynamicValidateDeleteForm = reactive({
    SNs: [
      {
        key: 1,
        value: '',
      },
    ]
  })

  

  const removeAddFormDomain = (domainItem) => {
    const index = dynamicValidateAddForm.SNs.indexOf(domainItem)
    if (index > 0) {
      dynamicValidateAddForm.SNs.splice(index, 1)
    }
  }
  const removeDeleteFormDomain = (domainItem) => {
    const index = dynamicValidateDeleteForm.SNs.indexOf(domainItem)
    if (index > 0) {
      dynamicValidateDeleteForm.SNs.splice(index, 1)
    }
  }

  const addSNAddDomain = () => {
    dynamicValidateAddForm.SNs.push({
      key: Date.now(),
      value: '',
    })
  }

  const addSNDeleteDomain = () => {
    dynamicValidateDeleteForm.SNs.push({
      key: Date.now(),
      value: '',
    })
  }

  //提交添加SN
  const submitAddSNForm = (formInstance) => {
    if (!formInstance) return
    formInstance.validate((valid) => {
      if (valid) {
        let addSNs = [];
        for (let SNItem of dynamicValidateAddForm.SNs) {
          addSNs.push(SNItem.value.trim())
        }

        //调用后端接口添加SNs
        axios({
          method: addSNsApi.method,
          url: addSNsApi.url,
          data: {
            projectName: dynamicValidateAddForm.projectName,
            sns: addSNs
          }
        }).then(response => {
          if (response.data.code == 200) {
            ElMessage({
              //showClose: true,
              duration: 3000,
              message: response.data.message,
              type: 'success',
            })

          } else {
            ElMessage({
              //showClose: true,
              duration: 3000,
              message: response.data.message,
              type: 'error',
            })
          }

        }).catch(err => {
          ElMessage.error(err)
        })
        console.log(dynamicValidateAddForm.projectName)
      } else {
        console.log('error submit!')
        return false
      }
    })
  }

  //提交删除SN
  const submitDeleteSNForm = (formInstance) => {
    if (!formInstance) return
    formInstance.validate((valid) => {
      if (valid) {
        let deleteSNs = [];
        for (let SNItem of dynamicValidateDeleteForm.SNs) {
          deleteSNs.push(SNItem.value.trim())
        }

        //调用后端接口删除SNs
        axios({
          method: deleteSNsApi.method,
          url: deleteSNsApi.url,
          data: {
            sns: deleteSNs
          }
        }).then(response => {
          if (response.data.code == 200) {
            ElMessage({
              //showClose: true,
              duration: 3000,
              message: response.data.message,
              type: 'success',
            })
          } else {
              ElMessage({
                //showClose: true,
                duration: 3000,
                message: response.data.message,
                type: 'error',
              })
          }

        }).catch(err => {
          ElMessage.error(err)
        })
        
      } else {
        console.log('error submit!')
        return false
      }
    })
  }

  const resetForm = (formInstance) => {
    if (!formInstance) return
    formInstance.resetFields()
  }


</script>

<template>
  <div class="home">
  
    <el-tabs type="border-card" v-model="currForm" @tab-click="changeForm">
      <el-tab-pane label="添加SN" name="1"></el-tab-pane>
      <el-tab-pane label="删除SN" name="2"></el-tab-pane>
      <el-tab-pane label="获取SN" name="3"></el-tab-pane>
      
        <el-form
        ref="addFormRef"
        style="max-width: 600px"
        :model="dynamicValidateAddForm"
        label-width="auto"
        class="demo-dynamic"
        v-show="currForm == 1? true : false"
      >
        <el-form-item
          prop="projectName"
          label="项目名称"
          :rules="[
            {
              required: true,
              message: '请输入项目名称',
              trigger: 'blur',
            }
          ]"
        >
          <el-input v-model="dynamicValidateAddForm.projectName" />
        </el-form-item>
        <el-form-item
          v-for="(SN, index) in dynamicValidateAddForm.SNs"
          :key="SN.key"
          :label="'SN' + (index+1)"
          :prop="'SNs.' + index + '.value'"
          :rules="{
            required: true,
            message: 'SN不能为空',
            trigger: 'blur',
          }"
        >
          <el-input v-model="SN.value" />
          <el-button class="mt-2" @click.prevent="removeAddFormDomain(SN)"
            >移除</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAddSNForm(addFormRef)">提交</el-button>
          <el-button @click="addSNAddDomain">添加选项</el-button>
          <el-button @click="resetForm(addFormRef)">重置</el-button>
        </el-form-item>
      </el-form>

      <el-form
        ref="deleteFormRef"
        style="max-width: 600px"
        :model="dynamicValidateDeleteForm"
        label-width="auto"
        class="demo-dynamic"
        v-show="currForm == 2? true : false"
      >
        <el-form-item
          v-for="(SN, index) in dynamicValidateDeleteForm.SNs"
          :key="SN.key"
          :label="'SN' + (index+1)"
          :prop="'SNs.' + index + '.value'"
          :rules="{
            required: true,
            message: 'SN不能为空',
            trigger: 'blur',
          }"
        >
          <el-input v-model="SN.value" />
          <el-button class="mt-2" @click.prevent="removeDeleteFormDomain(SN)"
            >移除</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitDeleteSNForm(deleteFormRef)">提交</el-button>
          <el-button @click="addSNDeleteDomain">添加选项</el-button>
          <el-button @click="resetForm(deleteFormRef)">重置</el-button>
        </el-form-item>
      </el-form>

<!--      <el-text class="mx-1" v-show="currForm == 3? true : false">-->
<!--        {{ SNsContent }}-->
<!--      </el-text>-->

      <!-- 条件查询表单 -->
      <el-form
          ref="conditionFormRef"
          style="max-width: 600px"
          :model="conditionForm"
          label-width="auto"
          class="demo-dynamic"
          v-show="currForm == 3"
      >
        <el-form-item
            prop="projectName"
            label="项目名称"
        >
          <el-select
              v-model="conditionForm.projectName"
              filterable
              clearable
              placeholder="请选择或输入项目名称"
              :loading="loadingProjects"
              style="width: 100%"
          >
            <el-option
                v-for="item in projectOptions"
                :key="item"
                :label="item"
                :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item
            prop="sns"
            label="SN"
        >
          <el-input v-model="conditionForm.sns" placeholder="输入设备SN码" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitConditionForm(conditionFormRef)">查询</el-button>
          <el-button @click="resetConditionForm(conditionFormRef)">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 查询结果显示 -->
      <div v-show="currForm == 3" style="margin-top: 20px;">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>查询结果</span>
            </div>
          </template>
          <el-text class="mx-1">
            <pre>{{ SNsContent }}</pre>
          </el-text>
        </el-card>
      </div>

    </el-tabs>
    


  </div>
    
</template>
  
<style>
  .home {
    width: 50%;
    margin: 0px auto;
  }

  .card-header {
    font-weight: bold;
  }

  pre {
    white-space: pre-wrap;
    word-wrap: break-word;
  }

</style>


