<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 Dialog from '@/components/dialog/Dialog.vue'
import TableBase from '@/components/TableBase/index.vue'
import type { FormInstance, FormRules } from 'element-plus'
import { Edit, Delete, Picture } from '@element-plus/icons-vue'
import type { ColumnProps } from '@/components/TableBase/interface/index'
import { ElNotification, ElMessageBox, ElMessage } from 'element-plus'

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: '产品型号' },
  { prop: 'T_spec', label: '产品规格' },
  { prop: 'T_relation_sn', label: '关联SN', name: 'T_relation_sn' },
  { prop: 'T_name', label: '更新时间' },
  { 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
    }
    console.log(form)
  })
  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('取消成功！')
    })
}

type Fn = () => void
const callbackDrawer = (done: Fn) => {
  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 url = ref('')
const srcList = ref<any[]>([])
const dialog = ref<InstanceType<typeof Dialog> | null>(null)
const previewImg = (str: string) => {
  dialog.value?.DialogOpen()
  url.value = str
  srcList.value.push(str)
}
// 获取产品分类
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 })
  console.log(res)
  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 }">
        <el-image
          v-if="row.T_img"
          style="width: 100px; height: 100px"
          :src="row.T_img"
          fit="cover"
          @click="previewImg(row.T_img)"
        />
        <el-image v-else style="width: 100px; height: 100px">
          <template #error>
            <div class="image-slot">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-image>
      </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-divider border-style="dashed" />
        <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-select v-model="form.T_spec" placeholder="请选择产品规格~">
            <el-option v-for="item in specList" :key="item.Id" :label="item.T_name" :value="item.T_name" />
          </el-select>
        </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"></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>
    <Dialog ref="dialog" width="50%">
      <el-image :src="url" :zoom-rate="1.2" :preview-src-list="srcList" fit="cover" />
    </Dialog>
  </div>
</template>

<style scoped lang="scss">
.production-list {
  height: 100%;
  .el-image {
    cursor: pointer;
  }
  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
  }
  .image-slot .el-icon {
    font-size: 30px;
  }
  .input-suffix {
    width: 100%;
    .inline-flex {
      white-space: nowrap;
    }
    .btn {
      display: flex;
      justify-content: end;
    }
    .w-50 {
      width: 12.5rem;
    }
  }
}
</style>
