<script setup lang="ts">
import { GlobalStore } from '@/stores/index'
import { ref, reactive, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import Drawer from '@/components/Drawer/index.vue'
import { ElMessage } from 'element-plus'
import TableBase from '@/components/TableBase/index.vue'
import { Edit, View } from '@element-plus/icons-vue'
import type { ColumnProps } from '@/components/TableBase/interface/index'
import type { FormInstance, FormRules } from 'element-plus'
import {
  Storehouse_VerifyContract_Add_Customer,
  Storehouse_VerifyContract_Customer_List,
  Storehouse_VerifyContract_Update_Customer
} from '@/api/storehouse/index'

const isNew = ref(true)
const router = useRouter()
const globalStore = GlobalStore()
const ruleFormRef = ref<FormInstance>()
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)
const TableRef = ref<InstanceType<typeof TableBase> | null>(null)

const columns: ColumnProps[] = [
  { type: 'index', label: '序号', width: 80 },
  { prop: 'T_customer', label: '客户名称' },
  { prop: 'T_start_date', label: '起始时间' },
  { prop: 'T_end_date', label: '终止时间' },
  { prop: 'T_State', label: '状态', name: 'T_State' },
  { prop: 'T_sign_times', label: '签约次数' },
  { prop: 'operation', label: '操作', width: 260, fixed: 'right' }
]
const options = reactive([
  { name: '已签约', id: 3 },
  { name: '已作废', id: 2 },
  { name: '未签约', id: 1 },
  { name: '即将到期', id: 4 }
])
const initParam = reactive({
  User_tokey: globalStore.GET_User_tokey,
  T_name: '',
  T_state: ''
})
const openContract = (type: string, row?: any) => {
  isNew.value = type === 'new' ? true : false
  if (type === 'edit') {
    form.value = { ...row }
  }
  drawerRef.value?.openDrawer()
}
const updateOnTableList = () => TableRef.value?.getTableList()
const processContract = (id: string) => router.push({ name: 'VerifyContractDetail', params: { id } })
const searchHandle = () => TableRef.value?.searchTable()
const callbackDrawer = (done: () => void) => {
  resetForm(ruleFormRef.value)
  done()
}
const form = ref({
  T_customer: '',
  T_customer_id: ''
})
const rules = reactive<FormRules>({
  T_customer: [{ required: true, message: '请输入客户名称', trigger: 'blur' }]
})
const AddContract = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      let res: any = {}
      if (isNew.value) {
        res = await Storehouse_VerifyContract_Add_Customer({ User_tokey: globalStore.GET_User_tokey, ...form.value })
      } else {
        res = await Storehouse_VerifyContract_Update_Customer({ User_tokey: globalStore.GET_User_tokey, ...form.value })
      }
      if (res.Code === 200) {
        ElMessage.success('添加客户成功！！')
        nextTick(() => {
          updateOnTableList()
          isNew.value = true
          resetForm(ruleFormRef.value)
          drawerRef.value?.closeDrawer()
        })
      }
    } else {
      return false
    }
  })
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>

<template>
  <div class="verify-contract">
    <TableBase
      ref="TableRef"
      :columns="columns"
      :requestApi="Storehouse_VerifyContract_Customer_List"
      :initParam="initParam"
    >
      <template #table-header>
        <el-row :gutter="20" style="margin-bottom: 0" class="input-suffix">
          <el-col :xl="6" :lg="8" :md="8" class="d-flex">
            <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-col>
          <el-col :xl="6" :md="8" class="d-flex">
            <span class="inline-flex items-center">状态：</span>
            <el-select v-model="initParam.T_state" class="w-50" clearable placeholder="请选择状态~">
              <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            <el-button type="primary" @click="searchHandle">搜索</el-button>
          </el-col>
          <el-col :xl="6" :md="2" :offset="4" class="btn"
            ><el-button type="primary" @click="openContract('new')">添加</el-button></el-col
          >
        </el-row>
      </template>
      <template #T_State="{ row }">
        <el-tag v-if="row.T_State === 1" type="warning" effect="dark"> 未签约 </el-tag>
        <el-tag v-else-if="row.T_State === 2" type="info" effect="dark"> 已作废 </el-tag>
        <el-tag v-else-if="row.T_State === 3" type="danger" effect="dark"> 已签约 </el-tag>
        <el-tag v-else type="danger" effect="dark"> 即将到期 </el-tag>
      </template>
      <template #right="{ row }">
        <el-button link type="primary" size="small" :icon="Edit" @click="openContract('edit', row)">编辑</el-button>
        <el-button link type="success" size="small" :icon="View" @click="processContract(row.T_customer_id)"
          >明细</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="客户名称：" label-width="100px" prop="T_customer">
          <el-input v-model="form.T_customer" type="text" autocomplete="off" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label-width="100px">
          <el-button v-if="isNew" color="#626aef" @click="AddContract(ruleFormRef)">提交</el-button>
          <el-button v-else color="#626aef" @click="AddContract(ruleFormRef)">修改</el-button>
        </el-form-item>
      </el-form>
    </Drawer>
  </div>
</template>

<style scoped lang="scss">
@import '@/styles/var.scss';

.verify-contract {
  @include f-direction;

  :deep(.el-drawer__header) {
    margin-bottom: 0;
  }
  .input-suffix {
    width: 100%;
    .inline-flex {
      white-space: nowrap;
    }
    .btn {
      display: flex;
      justify-content: end;
    }
    .w-50 {
      flex: 0 0 50%;
    }
  }
}
</style>
