<script lang="ts" setup name="ListApproval">
import type { PropType, Ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox, buttonEmits } from 'element-plus'
import type { IButton, ISupplier, IlistType, IlistTypes, supplierExportQuery } from '../list_interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getSoucreListDelete, getapprovalListPage } from '@/api/measure/source'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import { SCHEDULE } from '@/utils/scheduleDict'
import { submitApproval } from '@/api/approval'
const props = defineProps({
  status: {
    type: String,
    default: '0',
  },
  buttons: {
    type: Array as PropType<IButton[]>,
    default: () => [],
  },
})
const emit = defineEmits(['setData']) // 关闭

// 操作列宽度-计算属性
const operationWidth = computed(() => {
  return props.buttons.length * 32 + 24
})

// 查询条件
const listQuery: Ref<IlistTypes> = ref({
  approvalStatus: props.status,
  businessContent: '',
  companyArea: '',
  companyCity: '',
  companyProvince: '',
  formId: SCHEDULE.SUPPLIER_APPROVAL,
  supplierName: '',
  supplierNo: '',
  offset: 1,
  limit: 20,
})
// 控制是否显示新增页面
const show = ref(true)
// 表格数据
const list = ref<ISupplier[]>([])
// 总数
const total = ref(0)
// 控制审批操作弹窗的开关
const applyShow = ref(false)
// 表头
const columns = ref<TableColumn[]>([
  { text: '溯源供方编号', value: 'supplierNo', width: '160', align: 'center' },
  { text: '溯源供方名称', value: 'supplierName', width: '120', align: 'center' },
  { text: '业务内容', value: 'businessContent', align: 'center' },
  { text: '业务范围', value: 'businessScope', align: 'center' },
  { text: '负责人', value: 'director', align: 'center' },
  { text: '联系方式', value: 'phone', align: 'center' },
  { text: '地址', value: 'address', align: 'center' },
  { text: '创建时间', value: 'name', align: 'center' },
  { text: '审批状态', value: 'approvalStatusName', align: 'center' },
])
// 初始化路由
const $router = useRouter()
const buttonArray = ref<string[]>([])
// 选中的内容
const checkoutList = ref<string[]>([])
// 文件上传input
const fileRef = ref()
// 删除id
const deleteId = ref('')
// 详情id
const infoId = ref('0')
// 点击按钮
const buttonType = ref('')
const loadingTable = ref(false)
const fetchData = (isNowPage: boolean) => {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  getapprovalListPage(listQuery.value).then((response) => {
    list.value = response.data.rows
    // list.value = [
    //   { approvalStatus: '4', approvalStatusName: '已通过', bankAccount: '453', bankAccountNumber: '354', bankName: '543', briefName: '35431', businessContent: '5434', businessScope: '354', companyAddress: '2313', companyArea: '210103', companyCity: '210100', companyCountry: '中国', companyProvince: '210000', createTime: '2022-12-06 17:21:40', director: '354', fax: '354', id: '1600057880174956546', invoiceAddress: '213123', invoiceArea: '150302', invoiceCity: '150300', invoiceCountry: '中国', invoiceProvince: '150000', mailbox: '354', minioFileName: '', mobile: '354', phone: '354', postalCode: '534', remark: '', supplierName: '北京公司2', supplierNo: 'sygf202212060003', taxNumber: '3543', traceSupplierPersonList: [], website: '354' },
    // ]
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  }).catch((_) => {
    // list.value = [
    //   { approvalStatus: '4', approvalStatusName: '已通过', bankAccount: '453', bankAccountNumber: '354', bankName: '543', briefName: '35431', businessContent: '5434', businessScope: '354', companyAddress: '2313', companyArea: '210103', companyCity: '210100', companyCountry: '中国', companyProvince: '210000', createTime: '2022-12-06 17:21:40', director: '354', fax: '354', id: '1600057880174956546', invoiceAddress: '213123', invoiceArea: '150302', invoiceCity: '150300', invoiceCountry: '中国', invoiceProvince: '150000', mailbox: '354', minioFileName: '', mobile: '354', phone: '354', postalCode: '534', remark: '', supplierName: '北京公司2', supplierNo: 'sygf202212060003', taxNumber: '3543', traceSupplierPersonList: [], website: '354' },
    // ]
    loadingTable.value = false
  })
}
// fetchData(true)
// 多选发生改变时
const handleSelectionChange = (e: any) => {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}
// 点击删除和编辑的参数类型
interface rowReturn {
  id: string
  supplierName: string
}
const buttonTypeMap = ref('')
// 点击删除或者取消
const handleDelete = (row: rowReturn) => {
  ElMessageBox.confirm(
    '确认删除所选记录吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    getSoucreListDelete({ id: row.id }).then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        fetchData(true)
      }
    })
  })
}

// 取消
const handleCancel = (row: ISupplier) => {
  const params = {
    taskId: row.taskId!,
    comments: '',
  }
  ElMessageBox.confirm(
    '确认取消该审批吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(() => {
      submitApproval('revoke', params).then((res) => {
        ElMessage({
          type: 'success',
          message: '取消成功',
        })
        fetchData(true)
      })
    })
}

const approvalDialog = ref()

// 点击搜索
const searchList = () => {
  fetchData(false)
}
const cancelEvent = () => {
  console.log('cancel!')
}
// 点击重置
const clearList = () => {
  listQuery.value = {
    approvalStatus: props.status,
    businessContent: '',
    companyArea: '',
    companyCity: '',
    companyProvince: '',
    formId: SCHEDULE.SUPPLIER_APPROVAL,
    supplierName: '',
    supplierNo: '',
    offset: 1,
    limit: 20,
  }
}
// 导出
const exportExcelBtn = () => {
  const params: supplierExportQuery = {
    approvalStatus: listQuery.value.approvalStatus,
    businessContent: listQuery.value.businessContent,
    companyArea: listQuery.value.companyArea,
    companyCity: listQuery.value.companyCity,
    companyProvince: listQuery.value.companyProvince,
    formId: listQuery.value.formId,
    supplierName: listQuery.value.supplierName,
    supplierNo: listQuery.value.supplierNo,
  }
  if (checkoutList.value.length > 0) {
    params.ids = checkoutList.value
  }
  // TODO: 审批列表导出
  console.log(params)
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(255, 255, 255, 0.8)',
  })
  loading.close()
}

// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
const changePage = (val: { size?: number; page?: number }) => {
  if (val && val.size) {
    listQuery.value.limit = val.size
  }
  if (val && val.page) {
    listQuery.value.offset = val.page
  }
  fetchData(true)
}
// 跳转到详情
const goDetail = (row: ISupplier) => {
  $router.push(`approve/${props.status}/${row.id}`)
}
// 新建溯源供方
const add = () => {
  $router.push('/source/add')
}
// 批量导出
const exportAll = () => {
  exportExcelBtn()
}
// 审批结束回调
const approvalSuccess = () => {
  fetchData(true)
}
// 审批弹窗关闭
const handleClose = () => {
  applyShow.value = false
}

// 点击数据后的操作按钮
const clickBtn = (row: ISupplier, buttonType: string) => {
  switch (buttonType) {
    case '查看':
      goDetail(row)
      break
    case '编辑':
      $router.push(`/source/edit/${row.id}`)
      break
    case '同意':
      approvalDialog.value.initDialog('agree', row.taskId)
      break
    case '驳回':
      approvalDialog.value.initDialog('reject', row.taskId)
      break
    case '拒绝':
      approvalDialog.value.initDialog('refuse', row.taskId)
      break
    case '取消':
      handleCancel(row)
      break
    case '删除':
      handleDelete(row)
      break
  }
}

// 监听status变化，更新approvalStatus
watch (
  () => props.status,
  (newVal: string) => {
    console.log('change status')
    listQuery.value.approvalStatus = newVal
    fetchData(false)
  },
  { immediate: true })
// 打印
const printObj = ref({
  id: 'print', // 需要打印元素的id
  popTitle: '溯源供方列表', // 打印配置页上方的标题
  extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  standard: '',
  extarCss: '',
})
</script>

<template>
  <div v-if="show">
    <app-container>
      <search-area
        :need-clear="true"
        @search="searchList" @clear="clearList"
      >
        <search-item>
          <el-input v-model.trim="listQuery.supplierNo" placeholder="溯源供方编号" clearable />
        </search-item>
        <search-item>
          <el-input v-model.trim="listQuery.supplierName" placeholder="溯源供方名称" clearable />
        </search-item>
        <search-item>
          <el-input v-model.trim="listQuery.businessContent" placeholder="业务内容" clearable />
        </search-item>
        <search-item>
          <el-input v-model.trim="listQuery.businessContent" placeholder="地址" clearable />
        </search-item>
      </search-area>
      <table-container>
        <template #btns-right>
          <icon-button icon="icon-add" title="新建" type="primary" @click="add" />
          <icon-button icon="icon-export" title="导出" type="primary" @click="exportAll" />
          <icon-button v-print="printObj" icon="icon-print" title="打印" type="primary" />
        </template>
        <normal-table
          :data="list" :total="total" :columns="columns" :query="listQuery"
          :list-loading="loadingTable" is-showmulti-select @change="changePage" @multiSelect="handleSelectionChange"
        >
          <template #columns>
            <el-table-column label="操作" align="center" :width="operationWidth">
              <template #default="{ row }">
                <el-button
                  v-for="(item, index) in buttons"
                  :key="index"
                  size="small"
                  :type="item.type" link
                  @click="clickBtn(row, item.name)"
                >
                  {{ item.name }}
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
  </div>
  <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
</template>

