<script setup lang="ts">
import {
	exportOperationFile,
	Storehouse_Stock_Detail_Excel,
	Storehouse_VerifyContract_Add_Customer,
	Storehouse_VerifyContract_Customer_List,
	Storehouse_VerifyContract_Excel,
	Storehouse_VerifyContract_List,
	Storehouse_VerifyContract_Update_Customer
} from '@/api/storehouse'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ref, reactive, nextTick } 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'

const isNew = ref(true)
const router = useRouter()
const ruleFormRef = ref<FormInstance>()
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)
const customerTableRef = ref<InstanceType<typeof TableBase> | null>(null)
const detailTableRef = ref<InstanceType<typeof TableBase> | null>(null)
const { resetForm, globalStore, searchOnTableList, updateOnTableList } = useTablePublic()
const isDetailView = ref(false)

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 detailColumns: ColumnProps[] = [
  { type: 'index', label: '序号', width: 80 },
  { prop: 'T_customer', label: '公司名称' },
  { prop: 'T_number', label: '合同编号' },
  { prop: 'T_date', label: '签订时间' },
  { prop: 'T_discount', label: '金额' },
  { prop: 'T_start_date', label: '起始时间' },
  { prop: 'T_end_date', label: '终止时间' },
  { prop: 'T_stamping_date', label: '盖章时间' },
  { prop: 'T_payment_method', label: '付款方式', name: 'T_payment_method' },
  { prop: 'T_verify_state', label: '是否过期', name: 'T_verify_state' }
]
const detailInitParam = reactive({
  User_tokey: globalStore.GET_User_tokey,
  T_customer_id: '',
  T_customer_name: '',
  T_number: ''
})
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: 'VerifyContractDetail', params: { id } })
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 => {
    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(customerTableRef.value)
            isNew.value = true
            resetForm(ruleFormRef.value)
            drawerRef.value?.closeDrawer()
          })
        }
      })()
    }
  })
}
const toggleView = () => {
  isDetailView.value = !isDetailView.value
  nextTick(() => {
    const target = isDetailView.value ? detailTableRef.value : customerTableRef.value
    if (target) {
      updateOnTableList(target)
    }
  })
}
const visible = ref(false)
const exportExcel = () => (visible.value = true)
const T_date_detail = ref<string[]>([])
const confirmExport = async () => {

	try {
		const response: any = await Storehouse_VerifyContract_Excel({
			User_tokey: globalStore.GET_User_tokey,
			T_start_date: T_date_detail.value[0],
			T_end_date: T_date_detail.value[1],
			T_name: initParam.T_name,
			T_state: initParam.T_state,
		})

		// 处理返回的二进制文件并触发下载
		const blob = new Blob([response], {type: 'application/vnd.ms-excel;charset=utf8'})
		const url = window.URL.createObjectURL(blob)
		const a = document.createElement('a')
		a.href = url
		const now = new Date();
		const formattedDate = `${now.getFullYear()}${(now.getMonth()+1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}_${now.getHours().toString().padStart(2, '0')}${now.getMinutes().toString().padStart(2, '0')}`;
		a.download = `合同明细_${formattedDate}.xlsx`;
		document.body.appendChild(a)
		a.click()
		a.remove()
		window.URL.revokeObjectURL(url)
		ElMessage.success('导出成功')
	} catch (error) {
		ElMessage.error('导出失败，请检查网络连接')
	}

}

</script>

<template>
  <div class="verify-contract">
    <div class="view-toggle">
      <el-button plain type="primary" @click="toggleView">
        {{ isDetailView ? '返回客户列表' : '查看合同明细' }}
      </el-button>
    </div>
    <TableBase
      v-if="!isDetailView"
      ref="customerTableRef"
      :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" :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(customerTableRef)"
            />
          </el-col>
          <el-col :xl="10" :md="10" 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="searchOnTableList(customerTableRef)">搜索</el-button>
            <el-popover :visible="visible" placement="bottom" :width="400" trigger="click">
              <template #reference>
                <el-button type="success" @click="exportExcel">导出</el-button>
              </template>
              <el-date-picker
                v-model="T_date_detail"
                type="daterange"
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
              <div class="export-popover">
                <el-button size="small" @click="visible = false">取消</el-button>
                <el-button size="small" type="primary" @click="confirmExport">确认</el-button>
              </div>
            </el-popover>
          </el-col>
          <el-col :xl="8" :md="8" 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="success" 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>
    <TableBase
      v-else
      ref="detailTableRef"
      :columns="detailColumns"
      :requestApi="Storehouse_VerifyContract_List"
      :initParam="detailInitParam"
    >
      <template #table-header>
        <el-row :gutter="20" style="margin-bottom: 0" class="input-suffix">
          <el-col :xl="6" :md="6" class="d-flex">
            <span class="inline-flex items-center">公司名称：</span>
            <el-input
              v-model="detailInitParam.T_customer_name"
              type="text"
              class="w-50 m-2"
              placeholder="按公司名称搜索"
              @change="searchOnTableList(detailTableRef)"
            />
          </el-col>
          <el-col :xl="6" :md="6" class="d-flex">
            <span class="inline-flex items-center">合同编号：</span>
            <el-input
              v-model="detailInitParam.T_number"
              type="text"
              class="w-50 m-2"
              placeholder="按合同编号搜索"
              @change="searchOnTableList(detailTableRef)"
            />
          </el-col>
          <el-col :xl="12" :md="12" class="btn">
            <el-button type="primary" @click="searchOnTableList(detailTableRef)">搜索</el-button>
          </el-col>
        </el-row>
      </template>
      <template #T_payment_method="{ row }">
        <el-text v-if="row.T_payment_method === 'A'" type="info">先货后款</el-text>
        <el-text v-else-if="row.T_payment_method === 'B'" type="info">收部分定金50</el-text>
        <el-text v-else-if="row.T_payment_method === 'C'" type="info">先款后货</el-text>
        <el-text v-else>--</el-text>
      </template>
      <template #T_verify_state="{ row }">
        <el-tag v-if="row.T_verify_state === 1" type="warning" effect="dark"> 未签约 </el-tag>
        <el-tag v-else-if="row.T_verify_state === 2" type="info" effect="dark"> 已作废 </el-tag>
        <el-tag v-else-if="row.T_verify_state === 3" type="success" effect="dark"> 已签约 </el-tag>
        <el-tag v-else type="danger" effect="dark"> 即将到期 </el-tag>
      </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';
.export-popover {
	padding: 5px;
	display: flex;
	justify-content: center;
}

.verify-contract {
  @include f-direction;

  .view-toggle {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 10px;
  }

  :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>
