<template>
  <div class="app-container">
    <el-radio-group v-model="tabPosition" class="mb-30px">
      <el-radio-button label="craftInfo">工艺信息</el-radio-button>
      <el-radio-button label="deviceList">设备列表</el-radio-button>
      <el-radio-button label="Loto">锁定站</el-radio-button>
      <!--      <el-radio-button label="sopList">SOP列表</el-radio-button>-->
    </el-radio-group>

    <!-- 工艺信息 -->
    <div v-if="tabPosition === 'craftInfo'">
      <TinyMCE
        v-model:value="formData.remark"
        :height="700"
        placeholder="请输入内容..."
        @update:value="handleContentChange"
      />
      <el-button type="primary" @click="handleSave" :loading="loading">
        {{ loading ? '保存中...' : '保存内容' }}
      </el-button>
    </div>

    <!-- 设备列表 -->
    <div v-if="tabPosition === 'deviceList'">
      <ContentWrap>
        <el-button v-hasPermi="['iscs:machinery:create']" type="primary" plain @click="handleAdd">
          <Icon icon="ep:plus" />
          新增
        </el-button>

        <el-button
          v-hasPermi="['iscs:machinery:delete']"
          type="danger"
          plain
          :disabled="multiple"
          @click="handleDelete"
        >
          <Icon icon="ep:delete" />
          批量删除
        </el-button>
      </ContentWrap>
      <ContentWrap>
        <el-table
          v-loading="loading"
          :data="deviceList"
          row-key="machineryId"
          :default-expand-all="isExpandAll"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="id" label="设备编号" />
          <el-table-column prop="machineryName" label="设备名称" />
          <el-table-column prop="machineryImg" label="设备图">
            <template #default="{ row }">
              <el-image
                :src="row.machineryImg"
                :preview-src-list="[row.machineryImg]"
                fit="cover"
                class="w-50px h-50px"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="200">
            <template #default="{ row }">
              <el-button
                v-hasPermi="['iscs:machinery:update']"
                type="primary"
                link
                @click="handleUpdate(row)"
              >
                <Icon icon="ep:edit" />
                编辑
              </el-button>
              <el-button
                v-hasPermi="['iscs:machinery:delete']"
                type="danger"
                link
                @click="handleDelete(row)"
              >
                <Icon icon="ep:delete" />
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </div>

    <!-- LOTO站 -->
    <div v-if="tabPosition === 'Loto'">
      <ContentWrap>
        <MapData :machinery-id="route.query.machineryId" />
      </ContentWrap>
    </div>

    <!-- SOP列表 -->
    <div v-if="tabPosition === 'sopList'">
      <ContentWrap>
        <el-button
          v-hasPermi="['iscs:machinery:create']"
          type="primary"
          plain
          @click="handleAddSop"
        >
          <Icon icon="ep:plus" />
          新增
        </el-button>

        <el-button
          v-hasPermi="['iscs:machinery:delete']"
          type="danger"
          plain
          :disabled="multiple"
          @click="handleSopDelete"
        >
          <Icon icon="ep:delete" />
          批量删除
        </el-button>
      </ContentWrap>
      <ContentWrap>
        <el-table
          v-loading="loading"
          :data="sopList"
          row-key="sopId"
          @selection-change="handleSopSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="sopName" label="SOP名称" />
          <el-table-column prop="machineryName" label="工作内容" />
          <el-table-column label="操作" align="center" width="200">
            <template #default="{ row }">
              <el-button
                v-hasPermi="['iscs:machinery:edit']"
                type="primary"
                link
                @click="handleSopUpdate(row)"
              >
                <Icon icon="ep:edit" />
                编辑
              </el-button>
              <el-button
                v-hasPermi="['iscs:machinery:remove']"
                type="danger"
                link
                @click="handleSopDelete(row)"
              >
                <Icon icon="ep:delete" />
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-if="sopTotal > 0"
          v-model:total="sopTotal"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getSopList"
        />
      </ContentWrap>
    </div>

    <!-- 设备表单弹窗 -->
    <Dialog v-model="dialogVisible" :title="dialogTitle" width="800">
      <el-form
        ref="formRef"
        v-loading="formLoading"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="设备名称" prop="machineryName">
          <el-input v-model="formData.machineryName" placeholder="请输入设备名称" />
        </el-form-item>

        <!--        <el-row>-->
        <!--          <el-col :span="17">-->
        <!--            <el-form-item label="设备编号" prop="machineryCode">-->
        <!--              <el-input v-model="formData.machineryCode" placeholder="请输入设备编号" />-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--          <el-col :span="7">-->
        <!--            <el-form-item label-width="30">-->
        <!--              <el-switch-->
        <!--                v-model="autoGenFlag"-->
        <!--                active-text="自动生成"-->
        <!--                @change="handleAutoGenChange"-->
        <!--              />-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->

        <el-form-item label="岗位" prop="workstationId">
          <el-tree-select
            v-model="formData.workstationId"
            :data="workstationOptions"
            :props="{ label: 'workstationName', value: 'id', children: 'children' }"
            placeholder="请选择岗位"
            disabled
          />
        </el-form-item>

        <el-form-item label="所属电柜" prop="lotoId">
          <el-select
            v-model="formData.lotoId"
            placeholder="请选择所属电柜"
            class="!w-300px"
            disabled
          >
            <el-option
              v-for="dict in lotoOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="设备图" prop="machineryImg">
          <UploadImg v-model="formData.machineryImg" :limit="1" height="75px" width="75px" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </template>
    </Dialog>

    <!-- SOP表单弹窗 -->
    <Dialog v-model="sopDialogVisible" :title="sopDialogTitle" width="800">
      <el-form
        ref="sopFormRef"
        v-loading="formLoading"
        :model="sopFormData"
        :rules="sopFormRules"
        label-width="100px"
      >
        <el-form-item label="所属岗位" prop="workstationId">
          <el-tree-select
            v-model="sopFormData.workstationId"
            :data="workstationOptions"
            :props="defaultProps"
            placeholder="选择岗位"
            disabled
          />
        </el-form-item>

        <el-form-item label="设备/工艺" prop="machineryId">
          <el-tree-select
            v-model="sopFormData.machineryId"
            :data="machineryOptions"
            :props="defaultProps"
            placeholder="选择设备/工艺"
            disabled
          />
        </el-form-item>

        <el-form-item label="SOP类型" prop="sopType">
          <el-select v-model="sopFormData.sopType" placeholder="请选择SOP类型" clearable>
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.SOP_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button :disabled="formLoading" type="primary" @click="submitSopForm">确 定</el-button>
        <el-button @click="sopDialogVisible = false">取 消</el-button>
      </template>
    </Dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { useMessage } from '@/hooks/web/useMessage'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import * as TechnologyApi from '@/api/dv/technology'
import * as MardDeptApi from '@/api/system/marsdept/index'
import * as LotoApi from '@/api/dv/lotoStation'
import * as SopApi from '@/api/sop/index'

import MapData from './MapData.vue'
import TinyMCE from '@/components/TinyMCE/index.vue'

defineOptions({ name: 'TechnologyDetail' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const route = useRoute()

// 数据列表相关
const loading = ref(false)
const deviceList = ref([])
const sopList = ref([])
const total = ref(0)
const sopTotal = ref(0)
const multiple = ref(true)
const showSearch = ref(true)
const isExpandAll = ref(true)
const tabPosition = ref('craftInfo')

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  machineryName: undefined,
  machineryCode: undefined,
  machineryId: undefined
})

// 表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formRef = ref()
const formData = ref({
  id: undefined,
  parentId: undefined,
  machineryName: '',
  machineryCode: '',
  workstationId: undefined,
  lotoId: undefined,
  machineryImg: undefined,
  machineryType: '设备',
  remark: undefined
})
// 保存设备信息数据
const handleSave = async () => {
  if (!formData.value.remark.trim()) {
    return ElMessage.warning('请输入内容')
  }
  const data = await TechnologyApi.getTechnologyInfo(route.query.machineryId)
  formData.value.id = data.id
  formData.value.parentId = data.parentId
  formData.value.machineryName = data.machineryName
  formData.value.machineryCode = data.machineryCode
  formData.value.workstationId = data.workstationId
  formData.value.lotoId = data.lotoId
  formData.value.machineryImg = data.machineryImg
  formData.value.machineryType = data.machineryType
  loading.value = true

  try {
    await TechnologyApi.updateTechnology(formData.value)
    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
    console.error('API错误:', error)
  } finally {
    loading.value = false
  }
}
const handleContentChange = async (content: string) => {
  console.log('内容变化:', content)
  formData.value.remark = content
}

// 表单校验规则
const formRules = reactive({
  machineryName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
  // machineryCode: [{ required: true, message: '设备编号不能为空', trigger: 'blur' }],
  workstationId: [{ required: true, message: '岗位不能为空', trigger: 'blur' }],
  lotoId: [{ required: true, message: '电柜不能为空', trigger: 'blur' }]
})

// SOP表单相关
const sopDialogVisible = ref(false)
const sopDialogTitle = ref('')
const sopFormRef = ref()
const sopFormData = ref({
  sopId: undefined,
  workstationId: undefined,
  machineryId: undefined,
  sopType: undefined
})

// SOP表单校验规则
const sopFormRules = reactive({
  sopType: [{ required: true, message: 'SOP类型不能为空', trigger: 'change' }]
})

// 选项数据
const workstationOptions = ref([])
const machineryOptions = ref([])
const lotoOptions = ref([])
const defaultProps = {
  children: 'children',
  label: 'label'
}

// 自动生成编码
// const autoGenFlag = ref(false)

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = {
      ...queryParams,
      parentId: route.query.machineryId,
      machineryType: '设备'
    }
    const res = await TechnologyApi.listTechnology(data)
    const dataById = await TechnologyApi.getTechnologyInfo(route.query.machineryId)
    formData.value = dataById
    deviceList.value = res.list
    total.value = res.total
  } finally {
    loading.value = false
  }
}

/** 查询SOP列表 */
const getSopList = async () => {
  loading.value = true
  try {
    const data = {
      ...queryParams,
      machineryId: route.query.machineryId
    }
    const res = await SopApi.getSopPage(data)
    sopList.value = res.list
    sopTotal.value = res.total
  } finally {
    loading.value = false
  }
}

/** 获取选项数据 */
const getOptions = async () => {
  // 获取设备工艺树
  const techRes = await TechnologyApi.listTechnology({ pageNo: 1, pageSize: -1 })
  machineryOptions.value = techRes.list
  // 获取岗位树
  const marsRes = await MardDeptApi.listMarsDept({ pageNo: 1, pageSize: -1 })
  workstationOptions.value = marsRes.list

  // 获取电柜列表
  const lotoRes = await LotoApi.listLoto({ pageNo: 1, pageSize: -1 })
  lotoOptions.value = lotoRes.list.map((item) => ({
    value: item.id,
    label: item.lotoName
  }))
}

/** 打开设备表单 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)

  resetForm()
  if (id) {
    formLoading.value = true
    try {
      const data = await TechnologyApi.getTechnologyInfo(id)
      console.log(data, 'data')
      formData.value = data
    } finally {
      formLoading.value = false
    }
  } else {
    const detail = await TechnologyApi.getTechnologyInfo(route.query.machineryId)
    formData.value.lotoId = detail.lotoId
    formData.value.workstationId = detail.workstationId
    formData.value.parentId = route.query.machineryId
  }
}

/** 打开SOP表单 */
const openSop = async (type: string, id?: number) => {
  sopDialogVisible.value = true
  sopDialogTitle.value = t('action.' + type)
  resetSopForm()
  if (id) {
    formLoading.value = true
    try {
      sopFormData.value = await SopApi.selectSopById(id)
    } finally {
      formLoading.value = false
    }
  }
}

/** 新增设备 */
const handleAdd = async () => {
  open('create')
}

/** 新增SOP */
const handleAddSop = () => {
  openSop('create')
}

/** 修改设备 */
const handleUpdate = (row: any) => {
  open('update', row.id)
}

/** 修改SOP */
const handleSopUpdate = (row: any) => {
  openSop('update', row.sopId)
}

/** 删除设备 */
const handleDelete = async (row?: any) => {
  const ids = row?.id || selectedIds.value
  await message.confirm('确认删除数据项？')
  try {
    await TechnologyApi.delTechnology(ids)
    message.success(t('common.delSuccess'))
    getList()
  } catch {}
}

/** 删除SOP */
const handleSopDelete = async (row?: any) => {
  const ids = row?.sopId || selectedSopIds.value
  await message.confirm('确认删除数据项？')
  try {
    await SopApi.deleteSopList(ids)
    message.success(t('common.delSuccess'))
    getSopList()
  } catch {}
}

/** 提交设备表单 */
const submitForm = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  formLoading.value = true
  try {
    const data = formData.value
    if (data.id) {
      await TechnologyApi.updateTechnology(data)
      message.success(t('common.updateSuccess'))
    } else {
      await TechnologyApi.addTechnology(data)
      message.success(t('common.createSuccess'))
    }
    dialogVisible.value = false
    getList()
  } finally {
    formLoading.value = false
  }
}

/** 提交SOP表单 */
const submitSopForm = async () => {
  if (!sopFormRef.value) return
  const valid = await sopFormRef.value.validate()
  if (!valid) return
  formLoading.value = true
  try {
    const data = sopFormData.value
    if (data.sopId) {
      await SopApi.updateSop(data)
      message.success(t('common.updateSuccess'))
    } else {
      await SopApi.insertSop(data)
      message.success(t('common.createSuccess'))
    }
    sopDialogVisible.value = false
    getSopList()
  } finally {
    formLoading.value = false
  }
}

/** 自动生成编码 */
// const handleAutoGenChange = async (val: boolean) => {
//   if (val) {
//     const res = await genCode('TECHNOLOGY_CODE')
//     formData.value.machineryCode = res.data
//   } else {
//     formData.value.machineryCode = ''
//   }
// }

/** 重置设备表单 */
const resetForm = () => {
  formData.value = {
    machineryId: undefined,
    parentId: undefined,
    machineryName: '',
    machineryCode: '',
    workstationId: undefined,
    lotoId: undefined,
    machineryImg: undefined,
    machineryType: '设备'
  }
  formRef.value?.resetFields()
  // autoGenFlag.value = false
}

/** 重置SOP表单 */
const resetSopForm = () => {
  sopFormData.value = {
    sopId: undefined,
    workstationId: undefined,
    machineryId: undefined,
    sopType: undefined
  }
  sopFormRef.value?.resetFields()
}

/** 表格选择 */
const selectedIds = ref<number[]>([])
const handleSelectionChange = (selection: any[]) => {
  selectedIds.value = selection.map((item) => item.id)
  multiple.value = !selection.length
}

/** SOP表格选择 */
const selectedSopIds = ref<number[]>([])
const handleSopSelectionChange = (selection: any[]) => {
  selectedSopIds.value = selection.map((item) => item.sopId)
  multiple.value = !selection.length
}

onMounted(() => {
  getList()
  getSopList()
  getOptions()
})
</script>

<style scoped>
.app-container {
  width: 100%;
  height: 100%;
}

.mb-30px {
  margin-bottom: 30px;
}

.w-50px {
  width: 50px;
}

.h-50px {
  height: 50px;
}

.w-300px {
  width: 300px;
}
</style>
