<script setup lang="ts">
import {
  VerifyItem_List,
  VerifyItem_Add,
  VerifyItem_Edit,
  VerifyItem_Del,
} from '@/api/storehouse/index'
import { ref, reactive, nextTick } 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,options3 } 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_name', label: '项目名称' },
  { prop: 'T_type', label: '类型' , name: 'T_type'},
  { prop: 'T_price', label: '金额（元）' },
  { prop: 'operation', label: '操作', width: 150, fixed: 'right' }
]

const rules = reactive<FormRules>({
  T_name: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
  T_type: [{ required: true, message: '请选择类型', trigger: 'blur' }],
  T_price: [{ required: true, message: '请输入金额', trigger: 'blur' }],
})
const form:any = ref({
  T_id:'',
  T_name: '',
  T_type: 1,
  T_price: '',
})

const openDrawer = (type: string, row?: any) => {
  isNew.value = type === 'new' ? true : false
  if(type == 'edit'){
    form.value.T_id = row.Id
    form.value.T_name = row.T_name
    form.value.T_type = row.T_type
    form.value.T_price = row.T_price
  }else{
    delete form.value.T_id
    form.value.T_name = ''
    form.value.T_type = 1
    form.value.T_price =''
  }
  drawerRef.value?.openDrawer()
}

const AddProduction = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid: boolean) => {
    if (valid) {
      let res: any = {}
      if (isNew.value) {//新增
        res = await VerifyItem_Add({ User_tokey: globalStore.GET_User_tokey, ...form.value })
      } else {//编辑
        res = await VerifyItem_Edit({
          User_tokey: globalStore.GET_User_tokey,
          ...form.value,
        })
      }
      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 VerifyItem_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_type: ''
})
</script>

<template>
  <div class="production-list">
    <TableBase ref="TableRef" :columns="columns" :requestApi="VerifyItem_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-input
                v-model="initParam.T_name"
                type="text"
                class="w-50 m-2"
                placeholder="按项目名称搜索"
                @change="searchOnTableList(TableRef)"
              />
            </el-col>
            <el-col :xl="10" :md="12">
              <span class="inline-flex items-center">类型：</span>
              <el-select v-model="initParam.T_type" class="w-50 m-2" clearable placeholder="请选择分类~">
                <el-option v-for="item in options3" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
              <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_type="{ row }">
        <el-tag :type="row.T_type === 1?'success':'primary'" effect="dark">{{row.T_type === 1?'验证实施':'报告编写'}}</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" :disabled=!isNew autocomplete="off" placeholder="请填写项目名称" />
        </el-form-item>
        <el-form-item label="类型：" class="m-b-6" :label-width="formLabelWidth" prop="T_type">
          <el-radio-group v-model="form.T_type" class="ml-4">
            <el-radio :label="item.id" v-for="item in options3">{{item.name}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="金额：" class="m-b-6" :label-width="formLabelWidth" prop="T_price">
          <el-input v-model="form.T_price" type="text" autocomplete="off" 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>
