<script lang="ts" setup name="ReportOnCredentialslist">
import type { PropType, Ref } from 'vue'
import { getCurrentInstance, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IButton, ISupplier, IlistTypes, supplierExportQuery } from '@/views/measure/source/list_interface'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getSoucreListDelete, getapprovalListPage, sourceSubmit } from '@/api/measure/source'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import { printJSON } from '@/utils/printUtils'
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 { proxy } = getCurrentInstance() as any
// 操作列宽度-计算属性
const operationWidth = computed(() => {
  return props.buttons.length * 40 + 24
})

// 查询条件
const listQuery = ref({
  approvalStatus: props.status,
  businessContent: '',
  companyArea: '',
  companyCity: '',
  testCategory: '',
  companyProvince: '',
  formId: SCHEDULE.SUPPLIER_APPROVAL,
  supplierName: '',
  supplierNo: '',
  offset: 1,
  limit: 20,
})
// 控制是否显示新增页面
const show = ref(true)
// 表格数据
const list = ref([{ name: '张三', id: '1' }])
// 总数
const total = ref(0)
// 控制审批操作弹窗的开关
const applyShow = ref(false)
// 表头
const columns = ref<TableColumn[]>([
  { text: '证书号', value: 'name', align: 'center' },
  { text: '证书名称', value: 'name', width: '120', align: 'center' },
  { text: '样品编号', value: 'name', align: 'center' },
  { text: '样品名称', value: 'name', align: 'center' },
  { text: '型号', value: 'name', align: 'center' },
  { text: '出厂编号', value: 'name', align: 'center' },
  { text: '委托书编号', value: 'name', width: '120', align: 'center' },
  { text: '检校类别', value: 'name', align: 'center' },
  { text: '检定人员', value: 'name', align: 'center' },
  { text: '审批状态', value: 'name', align: 'center' },
  { text: '创建时间', value: 'name', align: 'center' },
])
// 初始化路由
const $router = useRouter()
const buttonArray = ref<string[]>([])
// 选中的内容
const checkoutList = ref<string[]>([])
// 表格loadingTable
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 testCategoryList = [
  { name: '检定', id: '1' },
  { name: '检测', id: '2' },
  { name: '验收鉴定', id: '3' },
  { name: '校准', id: '4' },
  { name: '测试', id: '5' },
]
// 取消
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: '',
    testCategory: '',
    formId: SCHEDULE.SUPPLIER_APPROVAL,
    supplierName: '',
    supplierNo: '',
    offset: 1,
    limit: 20,
  }
  fetchData(true)
}
// 导出
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(`/lab/reportOnCredentialsApproval/detail/${row.id}`)
}
// 新建证书报告
const add = () => {
  $router.push('/lab/reportOnCredentialsApproval/add')
}
// 批量导出
const exportAll = () => {
  exportExcelBtn()
}
// 审批结束回调
const approvalSuccess = () => {
  // fetchData(true)
}
// 审批弹窗关闭
const handleClose = () => {
  applyShow.value = false
}
// 提交
const approvalSubmit = (row: ISupplier) => {
  ElMessageBox.confirm('确认提交吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    sourceSubmit({ id: row.id, formId: SCHEDULE.SUPPLIER_APPROVAL }).then((res) => {
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '提交成功',
        })
        fetchData(true)
      }
    })
  })
}
// 点击数据后的操作按钮
const clickBtn = (row: ISupplier, buttonType: string) => {
  switch (buttonType) {
    case '查看':
      goDetail(row)
      break
    case '提交':
      approvalSubmit(row)
      break
    case '编辑':
      $router.push(`/lab/reportOnCredentialsApproval/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 })
// 打印列表
function printList() {
  // 打印列
  const properties = columns.value.map((item) => {
    return {
      field: item.value,
      displayName: item.text,
    }
  })
  if (checkoutList.value.length <= 0 && list.value.length > 0) {
    printJSON(list.value, properties, '证书报告列表')
  }
  // else if (checkoutList.value.length > 0) {
  //   const printList = list.value.filter((item: ISupplier) => checkoutList.value.includes(item.id))
  //   printJSON(printList, properties, '证书报告列表')
  // }
  else {
    ElMessage.warning('无可打印内容')
  }
}

onActivated(() => {
  // fetchData(true)
})
</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-item>
          <el-input v-model.trim="listQuery.businessContent" placeholder="样品名称" clearable />
        </search-item>
        <search-item>
          <el-select
            v-model="listQuery.testCategory"
            placeholder="请选择检测类别"
            style="width: 195px;"
            clearable
          >
            <el-option
              v-for="item in testCategoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </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 icon="icon-print" title="打印" type="primary" @click="printList" />
        </template>
        <normal-table
          :data="list" :total="total" :columns="columns" :query="listQuery"
          :list-loading="loadingTable" is-showmulti-select @change="changePage" @multi-select="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>

