<script setup lang="ts">
import {
  Storehouse_ProductClass_List,
  Storehouse_Product_List,
  Storehouse_Product_Add,
  Storehouse_Product_Edit,
  Storehouse_Product_Del,
  Storehouse_Product_Spec_List
} from '@/api/storehouse/index'
import { GlobalStore } from '@/stores/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'

const isNew = ref(true)
const globalStore = GlobalStore()
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 columns: ColumnProps[] = [
  { type: 'index', label: '序号', width: 80 },
  { prop: 'T_img', label: '产品图片', name: 'T_img' },
  { prop: 'T_name', label: '产品名称' },
  { prop: 'T_class_name', label: '产品分类' },
  { prop: 'T_model', label: '产品型号', ellipsis: true },
  { prop: 'T_spec', label: '产品规格' },
  { prop: 'T_relation_sn', label: '关联SN', name: 'T_relation_sn' },
  { 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' }]
})
const form = reactive({
  T_id: '',
  T_name: '',
  T_class: '',
  T_model: '',
  T_spec: '',
  T_relation_sn: '',
  T_img: '',
  T_remark: ''
})

const openDrawer = (type: string, row?: any) => {
  isNew.value = type === 'new' ? true : false
  !specList.value.length && getSpecList()
  nextTick(() => {
    if (!isNew.value) {
      form.T_id = row.Id
      form.T_img = row.T_img
      form.T_name = row.T_name
      form.T_spec = row.T_spec
      form.T_model = row.T_model
      form.T_class = row.T_class
      form.T_remark = row.T_remark
      form.T_relation_sn = row.T_relation_sn
    }
  })
  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 })
      } else {
        res = await Storehouse_Product_Edit({ User_tokey: globalStore.GET_User_tokey, ...form })
      }
      if (res.Code === 200) {
        ElMessage.success(`产品${isNew.value ? '添加' : '修改'}成功！！`)
        nextTick(() => {
          drawerRef.value?.closeDrawer()
          TableRef.value?.getTableList()
          resetForm(ruleFormRef.value)
          isNew.value = true
        })
      }
    } else {
      return false
    }
  })
}

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(() => {
          TableRef.value?.getTableList()
        })
      }
    })
    .catch(() => {
      ElMessage.warning('取消成功！')
    })
}

const callbackDrawer = (done: () => void) => {
  resetForm(ruleFormRef.value)
  done()
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  uploadRef.value?.clearfileList()
  formEl.resetFields()
}
// 搜索
const initParam = reactive({
  User_tokey: globalStore.GET_User_tokey,
  T_name: '',
  T_class: ''
})

const searchHandle = () => TableRef.value?.searchTable()

// 获取产品分类
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 specList = ref<any[]>([])
const getSpecList = async () => {
  const res: any = await Storehouse_Product_Spec_List({ User_tokey: globalStore.GET_User_tokey })
  specList.value = res.Data
}

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="searchHandle"
              />
              <el-button type="primary" @click="searchHandle">搜索</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_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_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>
