<script setup lang="ts">
import {
  Storehouse_VerifyContract_Add_Customer,
  Storehouse_VerifyContract_Recover_List,
  Storehouse_VerifyContract_Update_Customer
} from '@/api/storehouse'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ref, reactive, nextTick ,defineAsyncComponent} from 'vue'
import Drawer from '@/components/Drawer/index.vue'
import TableBase from '@/components/TableBase/index.vue'
import { Edit, View } from '@element-plus/icons-vue'
import type { ColumnProps } from '@/components/TableBase/interface'
import type { FormInstance, FormRules } from 'element-plus'
import { useTablePublic } from '@/hooks/useTablePublic'
import { fnMd5 } from '@/utils/common'
const isNew = ref(true)
const router = useRouter()
const ruleFormRef = ref<FormInstance>()
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)
const TableRef = ref<InstanceType<typeof TableBase> | null>(null)
const { resetForm, globalStore, searchOnTableList, updateOnTableList } = useTablePublic()

const customer_id = ref('')

const columns: ColumnProps[] = [
  { type: 'index', label: '序号', width: 80 },
  { prop: 'T_number', label: '合同编号' },
  { prop: 'T_customer', label: '客户名称' },
  { prop: 'T_type', label: '合同类型', name: 'T_type'},
  { prop: 'T_money', label: '合同总金额' },
  { prop: 'T_discount', label: '优惠金额' },
  { prop: 'T_recoveries_money', label: '回款金额' },
  { prop: 'T_invoice_money', label: '开票金额' },
  { prop: 'operation', label: '操作', width: 260, fixed: 'right' }
]
const options1 = reactive([
  { name: '未回款', id: 1 },
  { name: '部分回款', id: 2 },
  { name: '全部回款', id: 3 },

])

const options2 = reactive([
  { name: '未开票', id: 1 },
  { name: '部分开票', id: 2 },
  { name: '全部开票', id: 3 },

])

const ContractFormRef = ref<InstanceType<typeof ContractForm> | null>(null)
const VerifyFormRef = ref<InstanceType<typeof VerifyForm> | null>(null)
  //编辑弹出
const openContractFormDrawer = (type: string, row?: any) => {
  if (row.T_type==1) {
    ContractFormRef.value?.openDrawer(type, row)//12544
  } else {
    VerifyFormRef.value?.openDrawer(type, row)
  }
}


// const processContract = (id: string) => router.push({ name: 'VerifyContractDetail', params: { id } })

const ContractForm = defineAsyncComponent({
  loader: () => import(/*webpackChunkName: 'ContractForm'*/ '../sales/ContractForm.vue'),
  delay: 500,
  timeout: 3000,
  suspensible: true
})
const VerifyForm = defineAsyncComponent({
  loader: () => import(/*webpackChunkName: 'ContractForm'*/ '../sales/VerifyForm.vue'),
  delay: 500,
  timeout: 3000,
  suspensible: true
})

const initParam = reactive({
  User_tokey: globalStore.GET_User_tokey,
  T_name: '',
  T_recoveries_state: '',//回款状态
  T_invoice_state:''//开票状态
})
// const openContract = (type: string, row?: any) => {
//   isNew.value = type === 'new' ? true : false
//   if (type === 'edit') {
//     form.value = { ...row }
//   }
//   drawerRef.value?.openDrawer()
// }
//编辑弹出


const processContract = (id: string) => router.push({ name: 'ContractDetail', params: { id, type: fnMd5('contract') } })
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((valid: boolean) => {
    if (valid) {
      (async () => {
        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(TableRef.value)
            isNew.value = true
            resetForm(ruleFormRef.value)
            drawerRef.value?.closeDrawer()
          })
        }
      })()
    }
  })
}
</script>

<template>
  <div class="verify-contract">
    <TableBase
      ref="TableRef"
      :columns="columns"
      :requestApi="Storehouse_VerifyContract_Recover_List"
      :initParam="initParam"
    >
      <template #table-header>
        <el-row :gutter="20" style="margin-bottom: 0" class="input-suffix">
          <el-col :xl="6" :lg="6" :md="6" 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="searchOnTableList(TableRef)"
            />
          </el-col>
          <el-col :xl="6" :lg="6" :md="6" class="d-flex">
            <span class="inline-flex items-center">回款状态：</span>
            <el-select v-model="initParam.T_recoveries_state" class="w-50" clearable placeholder="请选择">
              <el-option v-for="item in options1" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
            
          </el-col>
          <el-col :xl="6" :lg="6" :md="6" class="d-flex">
            <span class="inline-flex items-center">开票状态：</span>
            <el-select v-model="initParam.T_invoice_state" class="w-50" clearable placeholder="请选择">
              <el-option v-for="item in options2" :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" :offset="4" class="btn">
            <el-button type="primary" @click="openContract('new')">添加</el-button>
          </el-col> -->
        </el-row>
      </template>
      <template #T_type="{ row }">
        <el-tag :type="row.T_type==1?'':'success'" effect="dark"> {{row.T_type==1?'销售合同':row.T_type==2?'验证合同':'-'}} </el-tag>
      </template>
      <template #right="{ row }">
        <el-button link type="primary" size="small" :icon="Edit" @click="openContractFormDrawer('edit', row)">编辑</el-button>
        <!-- <el-button link type="success" size="small" :icon="View" @click="processContract(row.T_number)">明细</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>
    <ContractForm ref="ContractFormRef" @onTableList="updateOnTableList(TableRef)" />
    <VerifyForm ref="VerifyFormRef" @onTableList="updateOnTableList(TableRef)" :verify_customer_id="customer_id" />
  </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>
