<script setup lang="ts">
import {
	Storehouse_VerifyCompany_List,
	VerifyItem_Add,
	Storehouse_VerifyCompany_Edit,
	Storehouse_VerifyCompany_Del, Storehouse_VerifyCompany_Add,
} 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,options4 } 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_State', label: '状态' , name: 'T_State'},
  { prop: 'T_recoveries_time', label: '回款时间'},
  { prop: 'operation', label: '操作', width: 150, fixed: 'right' }
]

const rules = reactive<FormRules>({
  T_name: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
  T_State: [{ required: true, message: '请选择状态', trigger: 'blur' }],
})
const form:any = ref({
  T_uuid:'',
  T_name: '',
  T_State: 1,
})

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

const AddVerifyCompany = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid: boolean) => {
    if (valid) {
      let res: any = {}
      if (isNew.value) {//新增
        res = await Storehouse_VerifyCompany_Add({ User_tokey: globalStore.GET_User_tokey, ...form.value })
      } else {//编辑
        res = await Storehouse_VerifyCompany_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 VerifyCompanyDelete = (row: any) => {
  ElMessageBox.confirm('您确定要删除该公司吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res: any = await Storehouse_VerifyCompany_Del({
        User_tokey: globalStore.GET_User_tokey,
        T_uuid: row.T_uuid
      })
      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_state: ''
})
</script>

<template>
  <div class="production-list">
    <TableBase ref="TableRef" :columns="columns" :requestApi="Storehouse_VerifyCompany_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_state" class="w-50 m-2" clearable placeholder="请选择状态~">
                <el-option v-for="item in options4" :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_State="{ row }">
        <el-tag :type="row.T_State === 1?'info':'success'" effect="dark">{{row.T_State === 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="VerifyCompanyDelete(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_State">
          <el-radio-group v-model="form.T_State" class="ml-4">
            <el-radio :label="item.id" v-for="item in options4">{{item.name}}</el-radio>
          </el-radio-group>
        </el-form-item>
		  <el-form-item label="回款时间：" :label-width="formLabelWidth" prop="T_recoveries_time">
			  <el-date-picker
				  class="my-date-picker"
				  style="width: 21.5rem"
				  v-model="form.T_recoveries_time"
				  type="date"
				  placeholder="选择日期"
				  format="YYYY-MM-DD"
				  value-format="YYYY-MM-DD"
			  />
		  </el-form-item>
        
        <el-form-item :label-width="formLabelWidth">
          <el-button v-if="isNew" color="#626aef" @click="AddVerifyCompany(ruleFormRef)">提交</el-button>
          <el-button v-else color="#626aef" @click="AddVerifyCompany(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>
