<script lang="ts" setup name="ListApproval">
import type { PropType, Ref } from 'vue'
import { getCurrentInstance, ref } from 'vue'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import type { IButton, ISupplier, IlistTypes, rowReturn, supplierExportQuery } from '../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 { cancelApproval, submitApproval } from '@/api/approval'
import type { IAddress } from '@/components/AddressSelect/address-interface'

const props = defineProps({
  status: {
    type: String,
    default: '0',
  },
  buttons: {
    type: Array as PropType<IButton[]>,
    default: () => [],
  },
})
const emit = defineEmits(['setData']) // 关闭
const companyAddress = ref<string[]>([]) // 公司地址

// 获取权限
const { proxy } = getCurrentInstance() as any
// 操作列宽度-计算属性
const operationWidth = computed(() => {
  // 审批中状态时候长度返回错误
  if (props.status === '3' || props.status === '6') {
    props.buttons.length = 4 // 传递长度 + 判断条件下显示按钮长度
  }
  return props.buttons.length * 40 + 23
})

// 查询条件
const listQuery: Ref<IlistTypes> = ref({
  approvalStatus: props.status,
  businessContent: '',
  companyArea: '', // 区
  companyCity: '', // 市
  companyProvince: '', // 省
  companyCountry: '', // 国家
  companyAreaName: '', // 区
  companyCityName: '', // 市
  companyCountryName: '', // 国家
  companyProvinceName: '', // 省
  formId: SCHEDULE.SUPPLIER_APPROVAL,
  supplierName: '',
  supplierNo: '',
  offset: 1,
  limit: 20,
})
// 控制是否显示新增页面
const show = ref(true)
// 表格数据
const list = ref<ISupplier[]>([])
// 总数
const total = ref(0)
// 表头
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', width: '110px' },
])
// 初始化路由
const $router = useRouter()
// 选中的内容
const checkoutList = ref<string[]>([])
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
    companyAddress.value = [response.data.rows[0].companyCountry, response.data.rows[0].companyProvince, response.data.rows[0].companyCity, response.data.rows[0].companyArea, response.data.rows[0].companyAddress]
    total.value = parseInt(response.data.total)
    console.log(companyAddress.value)
    loadingTable.value = false
  }).catch((_) => {
    loadingTable.value = false
  })
}
// fetchData(true)
// 多选发生改变时
const handleSelectionChange = (e: any) => {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}
// 公司地址变化后给对象赋值
function companyAddressChange(addressObj: IAddress) {
  listQuery.value.companyCountry = addressObj.country
  listQuery.value.companyProvince = addressObj.province
  listQuery.value.companyCity = addressObj.city
  listQuery.value.companyArea = addressObj.area
  listQuery.value.companyCountryName = addressObj.countryName
  listQuery.value.companyProvinceName = addressObj.provinceName
  listQuery.value.companyCityName = addressObj.cityName
  listQuery.value.companyAreaName = addressObj.areaName
}
// 点击删除或者取消
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 = {
    processInstanceId: row.processId!,
    comments: '取消审批',
  }
  ElMessageBox.confirm(
    '确认取消该审批吗？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    cancelApproval(params).then(() => {
      ElMessage.success('取消成功')
      fetchData(true)
    })
  })
}

const approvalDialog = ref()

// 点击搜索
const searchList = () => {
  fetchData(false)
}

// 点击重置
const clearList = () => {
  listQuery.value = {
    approvalStatus: props.status,
    businessContent: '',
    companyArea: '', // 区
    companyCity: '', // 市
    companyProvince: '', // 省
    companyCountry: '', // 国家
    companyAreaName: '', // 区
    companyCityName: '', // 市
    companyCountryName: '', // 国家
    companyProvinceName: '', // 省
    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: Omit<ISupplier, 'traceSupplierPersonList'>) => {
  $router.push({
    path: `approve/${props.status}/${row.id}`,
    query: { ...row },
  })
}
// 新建溯源供方
const add = () => {
  $router.push('/source/add')
}
// 批量导出
const exportAll = () => {
  exportExcelBtn()
}
// 审批结束回调
const approvalSuccess = () => {
  fetchData(true)
}

// 提交
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(`/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
  }
}

// 驳回后编辑
function editAgain(row: ISupplier) {
  $router.push(`/source/edit/${row.id}?from=reject`)
}

// 监听status变化，更新approvalStatus
watch (
  () => props.status,
  (newVal: string) => {
    console.log('change status', newVal)
    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>
          <address-select :is-show-detailed-address="false" :data="companyAddress" @on-change="companyAddressChange" />
          <!-- <el-input v-model.trim="listQuery.businessContent" placeholder="地址" clearable /> -->
        </search-item>
      </search-area>
      <table-container>
        <template #btns-right>
          <icon-button v-if="proxy.hasPerm('/measure/measureSource/approve/add')" icon="icon-add" title="新建" type="primary" @click="add" />
          <icon-button v-if="proxy.hasPerm('/measure/measureSource/approve/print')" 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 #preColumns>
            <el-table-column label="序号" width="55" align="center">
              <template #default="scope">
                {{ (listQuery.offset - 1) * listQuery.limit + scope.$index + 1 }}
              </template>
            </el-table-column>
          </template>
          <template #columns>
            <el-table-column label="操作" align="center" :width="operationWidth" fixed="right">
              <template #default="{ row }">
                <el-button
                  size="small"
                  type="primary"
                  link
                  @click="clickBtn(row, '查看')"
                >
                  查看
                </el-button>
                <el-button
                  v-if="proxy.hasPerm('/train/plan/approve/agree') && row.approvalStatusName === '待审批'"
                  size="small"
                  link
                  type="primary"
                  :disabled="row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中'"
                  @click="clickBtn(row, '同意')"
                >
                  同意
                </el-button>
                <el-button
                  v-if="proxy.hasPerm('/train/plan/approve/regect') && row.approvalStatusName === '待审批' && row.decisionItem !== 3"
                  size="small"
                  link
                  type="primary"
                  :disabled="row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中'"
                  @click="clickBtn(row, '驳回')"
                >
                  驳回
                </el-button>
                <el-button
                  v-if="proxy.hasPerm('/train/plan/approve/refuse') && row.approvalStatusName === '待审批' && row.decisionItem !== 2"
                  size="small"
                  link
                  type="danger"
                  :disabled="row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中'"
                  @click="clickBtn(row, '拒绝')"
                >
                  拒绝
                </el-button>
                <el-button
                  v-if="proxy.hasPerm('/train/plan/approve/edit') && row.approvalStatusName === '未通过-驳回' || row.approvalStatusName === '草稿箱' || row.approvalStatusName === '已取消'"
                  size="small"
                  link
                  type="primary"
                  @click="clickBtn(row, '编辑')"
                >
                  编辑
                </el-button>
                <el-button
                  v-if="row.approvalStatusName === '草稿箱' || row.approvalStatusName === '已取消'"
                  size="small"
                  link
                  type="primary"
                  @click="clickBtn(row, '提交')"
                >
                  提交
                </el-button>
                <!-- 是发起者且审批中可以取消 -->
                <el-button
                  v-if="proxy.hasPerm('/train/plan/approve/cancel') && row.approvalStatusName === '审批中'"
                  size="small"
                  link
                  type="info"
                  :disabled="row.approvalStatusName !== '审批中'"
                  @click="clickBtn(row, '取消')"
                >
                  取消
                </el-button>
                <!-- 发起者和有删除权限的可以删除，已通过未通过状态不可以删除 -->
                <el-button
                  v-if="proxy.hasPerm('/train/plan/approve/delete') && row.approvalStatusName !== '未通过' && row.approvalStatusName !== '已通过' && row.approvalStatusName !== '未通过-驳回'"
                  size="small"
                  link
                  type="danger"
                  :disabled="row.approvalStatusName === '未通过' || row.approvalStatusName === '已通过'"
                  @click="clickBtn(row, '删除')"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
    </app-container>
  </div>
  <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />
</template>

