<script setup lang="ts">
import {
  Storehouse_ProductClass_List,
  Storehouse_Product_List,
  Storehouse_Product_Add,
  Storehouse_Product_Edit,
  Storehouse_Product_Del,
  Storehouse_Product_Spec_List,
  stockInEditSort
} from '@/api/storehouse/index'
import { ref, reactive, nextTick, onMounted } from 'vue'
import Upload from '@/components/Upload/index.vue'
import Drawer from '@/components/Drawer/index.vue'
import TableBase from '@/components/TableBase/index.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Edit, Delete, Plus } from '@element-plus/icons-vue'
import type { ColumnProps } from '@/components/TableBase/interface/index'
import ImageCom from '@/components/Image/index.vue'
import { useTablePublic } from '@/hooks/useTablePublic'

const isNew = ref(true)
const formLabelWidth = ref('100px')
const ruleFormRef = ref<FormInstance>()
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)
const TableRef = ref<InstanceType<typeof TableBase> | null>(null)
const uploadRef = ref<InstanceType<typeof Upload> | null>(null)
const { resetForm, globalStore, searchOnTableList, updateOnTableList } = useTablePublic()

const columns: ColumnProps[] = [
  { type: 'index', label: '序号', width: 80 },
  { prop: 'T_img', label: '产品图片', name: 'T_img' },
  { prop: 'T_class_name', label: '产品分类' },
  { prop: 'T_name', label: '产品名称' },
  { prop: 'T_model', label: '产品型号', ellipsis: true },
  { prop: 'T_sort', label: '序号(双击)', ellipsis: true, name: 'T_sort' },
  { prop: 'T_spec', label: '产品规格' },
  { prop: 'T_relation_sn', label: '关联SN', name: 'T_relation_sn' },
  { prop: 'T_early_warning', label: '预警数量' },
  { prop: 'T_remark', label: '备注', name: 'T_remark' },
  { prop: 'operation', label: '操作', width: 150, fixed: 'right' }
]

const rules = reactive<FormRules>({
  T_name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  T_class: [{ required: true, message: '请选择产品分类', trigger: 'blur' }],
  T_model: [{ required: true, message: '请输入产品型号', trigger: 'blur' }],
  T_spec: [{ required: true, message: '请选择产品规格', trigger: 'blur' }],
  T_relation_sn: [{ required: true, message: '请选择关联SN', trigger: 'blur' }],
  T_early_warning: [{ required: true, message: '请输入预警数量', trigger: 'blur' }]
})
const form = ref({
  Id: '',
  T_name: '',
  T_class: '',
  T_model: '',
  T_spec: '',
  T_relation_sn: '',
  T_img: '',
  T_remark: '',
  T_early_warning: ''
})

const openDrawer = (type: string, row?: any) => {
  isNew.value = type === 'new' ? true : false
  nextTick(() => {
    if (!isNew.value) {
      form.value = { ...row }
    }
  })
  drawerRef.value?.openDrawer()
}

const AddProduction = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      let res: any = {}
      if (isNew.value) {
        res = await Storehouse_Product_Add({ User_tokey: globalStore.GET_User_tokey, ...form.value })
      } else {
        res = await Storehouse_Product_Edit({
          User_tokey: globalStore.GET_User_tokey,
          ...form.value,
          T_id: form.value.Id
        })
      }
      if (res.Code === 200) {
        ElMessage.success(`产品${isNew.value ? '添加' : '修改'}成功！！`)
        nextTick(() => {
          drawerRef.value?.closeDrawer()
          updateOnTableList(TableRef.value)
          resetForm(ruleFormRef.value)
          isNew.value = true
        })
      }
    }
  })
}

const ProductDelete = (row: any) => {
  ElMessageBox.confirm('您确定要删除该产品吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res: any = await Storehouse_Product_Del({
        User_tokey: globalStore.GET_User_tokey,
        T_id: row.Id
      })
      if (res.Code === 200) {
        ElMessage.success('删除成功！')
        nextTick(() => updateOnTableList(TableRef.value))
      }
    })
    .catch(() => {
      ElMessage.warning('取消成功！')
    })
}

const callbackDrawer = (done: () => void) => {
  resetForm(ruleFormRef.value)
  uploadRef.value?.clearfileList()
  done()
}
// 搜索
const initParam = reactive({
  User_tokey: globalStore.GET_User_tokey,
  T_name: '',
  T_class: ''
})
// 获取产品分类
const options = ref<any[]>([])
const getProductClassList = async () => {
  const res: any = await Storehouse_ProductClass_List({ page: 1, page_z: 999 })
  options.value = res.Data.Data
}
const onclickSort = async (row:any)=>{
    ElMessageBox.prompt('请输入排序号', '', {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        inputValue:`${row.T_sort}`
    }).then(async({ value }) => {
       const result:any = await stockInEditSort({T_id:row.Id,T_sort:value})
       if(result.Code==200){
            ElMessage.success('编辑成功')
            TableRef.value?.getTableList()
       }
    }).catch(() => {})
}

onMounted(() => {
  getProductClassList()
})
</script>

<template>
  <div class="production-list">
    <TableBase ref="TableRef" :columns="columns" :requestApi="Storehouse_Product_List" :initParam="initParam">
      <template #table-header>
        <div class="input-suffix">
          <el-row :gutter="20" style="margin-bottom: 0">
            <el-col :xl="6" :lg="8" :md="10">
              <span class="inline-flex items-center">产品分类：</span>
              <el-select v-model="initParam.T_class" class="w-50 m-2" clearable placeholder="请选择分类~">
                <el-option v-for="item in options" :key="item.Id" :label="item.T_name" :value="item.Id" />
              </el-select>
            </el-col>
            <el-col :xl="10" :md="12">
              <span class="inline-flex items-center">产品名称：</span>
              <el-input
                v-model="initParam.T_name"
                type="text"
                class="w-50 m-2"
                placeholder="按产品名称、产品型号搜索"
                @change="searchOnTableList(TableRef)"
              />
              <el-button type="primary" @click="searchOnTableList(TableRef)">搜索</el-button>
            </el-col>
            <el-col :xl="6" :md="2" class="btn"
              ><el-button type="primary" @click="openDrawer('new')">添加</el-button></el-col
            >
          </el-row>
        </div>
      </template>

      <template #T_img="{ row }">
        <ImageCom :src="row.T_img" />
      </template>
      <template #T_sort="{ row }">
        <div @dblclick="onclickSort(row)" style="cursor: pointer;">
            {{ row.T_sort }}
          </div>
      </template>
      <template #T_remark="{ row }">
        <el-tooltip effect="customized" placement="left">
          <template #content>
            <div class="tooltip-content">{{ row.T_remark }}</div>
          </template>
          {{ row.T_remark }}
        </el-tooltip>
      </template>
      <template #T_relation_sn="{ row }">
        <el-tag v-if="row.T_relation_sn === 1" effect="dark">是</el-tag>
        <el-tag v-else type="success" effect="dark">否</el-tag>
      </template>
      <template #right="{ row }">
        <el-button link type="primary" size="small" :icon="Edit" @click="openDrawer('edit', row)">编辑</el-button>
        <el-button link type="danger" size="small" :icon="Delete" @click="ProductDelete(row)">删除</el-button>
      </template>
    </TableBase>
    <Drawer ref="drawerRef" :handleClose="callbackDrawer">
      <template #header="{ params }">
        <h4 :id="params.titleId" :class="params.titleClass">{{ isNew ? '添加' : '编辑' }} - 产品</h4>
      </template>
      <el-form ref="ruleFormRef" :model="form" :rules="rules">
        <el-form-item label="产品名称：" class="m-b-6" :label-width="formLabelWidth" prop="T_name">
          <el-input v-model="form.T_name" type="text" autocomplete="off" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="产品分类：" class="m-b-6" :label-width="formLabelWidth" prop="T_class">
          <el-select v-model="form.T_class" placeholder="请选择产品分类~">
            <el-option v-for="item in options" :key="item.Id" :label="item.T_name" :value="item.Id" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品型号：" class="m-b-6" :label-width="formLabelWidth" prop="T_model">
          <el-input v-model="form.T_model" type="text" autocomplete="off" placeholder="请输入产品型号" />
        </el-form-item>
        <el-form-item label="产品规格：" class="m-b-6" :label-width="formLabelWidth" prop="T_spec">
          <el-input v-model="form.T_spec" type="text" autocomplete="off" placeholder="请选择产品规格" />
        </el-form-item>
        <el-form-item label="关联SN：" class="m-b-6" :label-width="formLabelWidth" prop="T_relation_sn">
          <el-radio-group v-model="form.T_relation_sn" class="ml-4">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="预警数量：" class="m-b-6" :label-width="formLabelWidth" prop="T_early_warning">
            <el-input v-model="form.T_early_warning" type="text" autocomplete="off" placeholder="请收入预警数量" />
        </el-form-item>
        <el-form-item label="产品图片：" class="m-b-6" :label-width="formLabelWidth" prop="T_img">
          <!-- <Upload ref="uploadRef" v-if="isNew || form.T_img" :isImg="true" :limit="1" v-model="form.T_img"></Upload> -->
          <Upload ref="uploadRef" :isImg="true" :limit="1" v-model="form.T_img" accept="image/*">
            <el-icon><Plus /></el-icon>
          </Upload>
        </el-form-item>
        <el-form-item label="备注：" class="m-b-6" :label-width="formLabelWidth" prop="T_remark">
          <el-input
            v-model="form.T_remark"
            :autosize="{ minRows: 4, maxRows: 6 }"
            type="textarea"
            placeholder="请输入备注信息"
          />
        </el-form-item>
        <el-form-item :label-width="formLabelWidth">
          <el-button v-if="isNew" color="#626aef" @click="AddProduction(ruleFormRef)">提交</el-button>
          <el-button v-else color="#626aef" @click="AddProduction(ruleFormRef)">修改</el-button>
        </el-form-item>
      </el-form>
    </Drawer>
  </div>
</template>

<style scoped lang="scss">
@import '@/styles/var.scss';
.tooltip-content {
  max-width: 500px;
  overflow-y: auto;
}
.production-list {
  @include f-direction;
  .input-suffix {
    width: 100%;
    .inline-flex {
      white-space: nowrap;
    }
    .btn {
      display: flex;
      justify-content: end;
    }
    .w-50 {
      width: 12.5rem;
    }
  }
}
</style>
