<!-- 收入合同管理列表 -->
<script lang="ts" setup name="ContractList">
import type { Ref } from 'vue'
import type { DateModelType } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import type { IList, IListQuery, dictType } from './contract-interface'
import { printJSON } from '@/utils/printUtils'
import { exportFile } from '@/utils/exportUtils'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getDictByCode } from '@/api/system/dict'
import { SCHEDULE } from '@/utils/scheduleDict'
import { cancelApproval } from '@/api/approval'
import type { IMenu } from '@/components/buttonBox/buttonBox'
import ApprovalDialog from '@/components/Approval/ApprovalDialog.vue'
import { delContractList, getContractList, submitContractList } from '@/api/finance/contract'
import { calc } from '@/utils/useCalc'
const $router = useRouter()
const { proxy } = getCurrentInstance() as any
const active = ref('')
const TabActiveButton = 'FinanceContractApproveActive'
const approvalDialog = ref() // 审批对话ref
// 查询条件
const listQuery: Ref<IListQuery> = ref({
  agreementKind: '1', // 合同种类-收入合同1
  agreementName: '', // 合同名字
  agreementNo: '', // 合同编号
  agreementType: '', // 合同类型-采购合同/业务合同等-字典code
  customerId: '', // 单位id（客户id）（收入合同该字段为甲方单位，支出合同该字段为乙方单位）
  estimateSignEndDate: '', // 预计签订/实际签订结束日期
  estimateSignStartDate: '', // 预计签订/实际签订开始日期
  firstParty: '', // 单位名字（收入合同该字段为甲方单位，支出合同该字段为乙方单位）
  formId: SCHEDULE.BUSINESS_FINANCE_CONTRACT_APPROVE, // 表单id
  ids: [], // 导出ids
  status: '', // 合同完成状态-字典code
  approvalStatus: active.value, // 审批状态类型
  offset: 1,
  limit: 20,
})
const total = ref(0) // 数据条数
const loadingTable = ref(false) // 表格loading
const menu = ref<IMenu[]>([]) // 审批状态按钮组合
// 表头
const columns = ref<TableColumn[]>([
  { text: '合同编号', value: 'agreementNo', align: 'center', width: '140' },
  { text: '合同名称', value: 'agreementName', align: 'center' },
  { text: '合同类型', value: 'agreementTypeName', align: 'center' },
  { text: '创建人', value: 'createUserName', align: 'center' },
  { text: '部门', value: 'deptName', align: 'center' },
  { text: '签订日期', value: 'estimateSignDate', align: 'center', width: '110px' },
  { text: '合同金额(元)', value: 'agreementAmount', align: 'center', width: '90px' },
  { text: '甲方单位', value: 'firstParty', align: 'center' },
  { text: '创建时间', value: 'createTime', align: 'center', width: '180px' },
  { text: '合同完成状态', value: 'statusName', align: 'center' },
  { text: '审批状态', value: 'approvalStatusName', align: 'center', width: '110px' },
])
const list = ref<IList[]>([]) // 表格数据
// 筛选时间段数据
const dateRange = ref<[DateModelType, DateModelType]>(['', ''])
// 选中的内容
const checkoutList = ref<string[]>([])
// 时间变更
watch(dateRange, (val) => {
  if (val) {
    listQuery.value.estimateSignStartDate = `${val[0]}`
    listQuery.value.estimateSignEndDate = `${val[1]}`
  }
  else {
    listQuery.value.estimateSignStartDate = ''
    listQuery.value.estimateSignEndDate = ''
  }
})
// 数据查询
function fetchData(isNowPage = false) {
  loadingTable.value = true
  if (!isNowPage) {
    // 是否显示当前页，否则跳转第一页
    listQuery.value.offset = 1
  }
  // listQuery.value.estimateSignStartDate = dateRange.value[0] as string || ''
  // listQuery.value.estimateSignEndDate = dateRange.value[1] as string || ''
  getContractList(listQuery.value).then((response) => {
    list.value = response.data.rows.map((item: { estimateSignDate: string; agreementAmount: number }) => {
      return {
        ...item,
        estimateSignDate: item.estimateSignDate ? dayjs(item.estimateSignDate).format('YYYY-MM-DD') : item.estimateSignDate,
        agreementAmount: calc(Number(item.agreementAmount), 100, '/'),
      }
    })
    total.value = parseInt(response.data.total)
    loadingTable.value = false
  }).catch(() => {
    loadingTable.value = false
  })
}
// 搜索
const searchList = () => {
  fetchData(true)
}

// 重置
const reset = () => {
  listQuery.value = {
    agreementKind: '1', // 合同种类-1收入合同
    agreementName: '', // 合同名字
    agreementNo: '', // 合同编号
    agreementType: '', // 合同类型-采购合同/业务合同等-字典code
    customerId: '', // 单位id（客户id）（收入合同该字段为甲方单位，支出合同该字段为乙方单位）
    estimateSignEndDate: '', // 预计签订/实际签订结束日期
    estimateSignStartDate: '', // 预计签订/实际签订开始日期
    firstParty: '', // 单位名字（收入合同该字段为甲方单位，支出合同该字段为乙方单位）
    formId: SCHEDULE.BUSINESS_FINANCE_CONTRACT_APPROVE, // 表单id
    ids: [], // 导出ids
    status: '', // 合同完成状态-字典code
    approvalStatus: active.value, // 审批状态类型
    offset: 1,
    limit: 20,
  }
  dateRange.value = ['', '']
  fetchData(true)
}

// 多选发生改变时
function handleSelectionChange(e: any) {
  checkoutList.value = e.map((item: { id: string }) => item.id)
}

const contractTypeMap = ref<dictType[]>([]) // 合同类型
const contractStatusMap = ref<dictType[]>([]) // 合同完成状态
const contractKindMap = ref<dictType[]>([]) // 合同种类

// 查询字典
const getDict = async () => {
  // 审批状态
  const res = await getDictByCode('approvalStatus')
  // 制作右上角的菜单
  res.data.forEach((item: dictType) => {
    if (item.name === '全部' || item.name === '草稿箱'
      || item.name === '待审批' || item.name === '审批中'
      || item.name === '已通过' || item.name === '未通过'
      || item.name === '已取消') {
      menu.value.push({
        name: item.name,
        id: `${item.value}`,
      })
    }
  })
  // 合同类型
  getDictByCode('agreementType').then((response) => {
    contractTypeMap.value = response.data
  })
  // 合同完成状态
  getDictByCode('agreementStatus').then((response) => {
    contractStatusMap.value = response.data
  })
  // 合同种类
  getDictByCode('agreementKind').then((response) => {
    contractKindMap.value = response.data
  })
}

// 新建
const add = () => {
  $router.push({ path: '/contractManagement/add' })
}

// 打印列表
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: IList) => checkoutList.value.includes(item.id))
    printJSON(printList, properties, '收入合同管理列表')
  }
  else {
    ElMessage.warning('无可打印内容')
  }
}
// 页数发生变化后的操作，可能是页码变化，可能是每页容量变化，此函数必写
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)
}

// 切换tab状态
const changeCurrentButton = (val: string) => {
  active.value = val
  window.sessionStorage.setItem(TabActiveButton, val)
  reset()
}

// 操作
const handleEdit = (row: IList, val: string, title = '') => {
  if (val === '取消') {
    const params = {
      processInstanceId: row.processId!,
      comments: '',
    }
    ElMessageBox.confirm(
      '确认取消该审批吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        cancelApproval(params).then((res) => {
          ElMessage({
            type: 'success',
            message: '取消成功',
          })
          fetchData(true)
        })
      })
  }
  else if (val === '删除') {
    ElMessageBox.confirm(
      '确认删除吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        delContractList({ id: row.id }).then((res) => {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          fetchData(true)
        })
      })
  }
  else if (val === '提交') {
    ElMessageBox.confirm(
      '确认提交该审批吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )
      .then(() => {
        submitContractList({ id: row.id, formId: SCHEDULE.BUSINESS_FINANCE_CONTRACT_APPROVE, processId: row.processId }).then((res) => {
          ElMessage({
            type: 'success',
            message: '已提交',
          })
          fetchData(true)
        })
      })
  }
  else if (val === '同意') {
    approvalDialog.value.initDialog('agree', row.taskId)
  }
  else if (val === '驳回') {
    approvalDialog.value.initDialog('reject', row.taskId)
  }
  else if (val === '拒绝') {
    approvalDialog.value.initDialog('refuse', row.taskId)
  }
  else if (val === 'detail' || val === 'edit') { // 详情和编辑
    $router.push({
      path: `/contractManagement/${val}/${row.id}`,
      query: {
        approvalStatusName: row.approvalStatusName, // 审批状态名称
        processId: row.processId, // 流程实例
        decisionItem: `${row.decisionItem}`, // 同意、驳回、拒绝
        taskId: row.taskId,
      },
    })
  }
}

// 审批结束回调
const approvalSuccess = () => {
  fetchData(true)
}
const $route = useRoute()
onMounted(async () => {
  await getDict()
  if (window.sessionStorage.getItem(TabActiveButton)) {
    active.value = window.sessionStorage.getItem(TabActiveButton)!
  }
  else {
    active.value = menu.value.find(item => item.name === '全部')!.id as string // 全部
  }
  console.log('pppp=================================ppp')

  console.log($router.options.history.state.back)

  if ($router.options.history.state.back === '/comprehensive/approve') {
    active.value = menu.value.find(item => item.name === '待审批')!.id as string // 全部
  }
})
</script>

<template>
  <div>
    <!-- 布局 -->
    <app-container>
      <search-area :need-clear="true" @search="searchList" @clear="reset">
        <search-item>
          <el-input v-model.trim="listQuery.agreementNo" placeholder="合同编号" class="short-input" clearable />
        </search-item>
        <search-item>
          <el-input v-model.trim="listQuery.agreementName" placeholder="合同名称" class="short-input" clearable />
        </search-item>
        <search-item>
          <el-select v-model="listQuery.agreementType" placeholder="合同类型" clearable class="short-input">
            <el-option v-for="item in contractTypeMap" :key="item.id" :label="item.name" :value="item.value" />
          </el-select>
        </search-item>
        <search-item>
          <el-input v-model.trim="listQuery.firstParty" placeholder="甲方单位" class="short-input" clearable />
        </search-item>
        <search-item>
          <el-date-picker
            v-model="dateRange"
            class="short-input"
            type="daterange"
            range-separator="到"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            start-placeholder="签订开始日期"
            end-placeholder="签订结束日期"
          />
        </search-item>
        <search-item>
          <el-select v-model="listQuery.status" class="short-input" placeholder="合同完成状态" clearable>
            <el-option v-for="item in contractStatusMap" :key="item.id" :label="item.name" :value="item.value" />
          </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-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"
              fixed="right"
              :width="(active === '0') ? 150 : (active === '1' || active === '6') ? 150 : (active === '4' || active === '5' || active === '3') ? 100 : 150"
            >
              <template #default="{ row }">
                <el-button
                  size="small"
                  type="primary"
                  link
                  @click="handleEdit(row, 'detail')"
                >
                  查看
                </el-button>
                <el-button
                  v-if="row.approvalStatusName === '待审批'"
                  size="small"
                  link
                  type="primary"
                  :disabled="row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中'"
                  @click="handleEdit(row, '同意')"
                >
                  同意
                </el-button>
                <el-button
                  v-if="row.approvalStatusName === '待审批' && row.decisionItem !== 3"
                  size="small"
                  link
                  type="primary"
                  :disabled="row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中'"
                  @click="handleEdit(row, '驳回')"
                >
                  驳回
                </el-button>
                <el-button
                  v-if="row.approvalStatusName === '待审批' && row.decisionItem !== 2"
                  size="small"
                  link
                  type="danger"
                  :disabled="row.approvalStatusName !== '待审批' && row.approvalStatusName !== '审批中'"
                  @click="handleEdit(row, '拒绝')"
                >
                  拒绝
                </el-button>
                <el-button
                  v-if="row.approvalStatusName === '未通过-驳回' || row.approvalStatusName === '草稿箱' || row.approvalStatusName === '已取消'"
                  size="small"
                  link
                  type="primary"
                  @click="handleEdit(row, 'edit')"
                >
                  编辑
                </el-button>
                <el-button
                  v-if="row.approvalStatusName === '草稿箱' || row.approvalStatusName === '已取消'"
                  size="small"
                  link
                  type="primary"
                  @click="handleEdit(row, '提交')"
                >
                  提交
                </el-button>

                <!-- 是发起者且审批中可以取消 -->
                <el-button
                  v-if="row.approvalStatusName === '审批中'"
                  size="small"
                  link
                  type="info"
                  :disabled="row.approvalStatusName !== '审批中'"
                  @click="handleEdit(row, '取消')"
                >
                  取消
                </el-button>
                <!-- 发起者和有删除权限的可以删除，已通过未通过状态不可以删除 -->
                <!-- <el-button
                v-if="row.approvalStatusName !== '未通过' && row.approvalStatusName !== '已通过' && row.approvalStatusName !== '未通过-驳回'"
                size="small"
                link
                type="danger"
                :disabled="row.approvalStatusName === '未通过' || row.approvalStatusName === '已通过'"
                 @click="handleEdit(row, '删除')"
              >
                删除
              </el-button> -->
                <!-- ---------------------------审批中的删除按钮暂时去掉------------------------ -->
                <el-button
                  v-if="row.approvalStatusName !== '未通过' && row.approvalStatusName !== '已通过' && row.approvalStatusName !== '未通过-驳回' && row.approvalStatusName !== '审批中' && row.approvalStatusName !== '待审批'"
                  size="small"
                  link
                  type="danger"
                  :disabled="row.approvalStatusName === '未通过' || row.approvalStatusName === '已通过'"
                  @click="handleEdit(row, '删除')"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </table-container>
      <!-- 审批弹窗 -->
      <approval-dialog ref="approvalDialog" @on-success="approvalSuccess" />

      <button-box :active="active" :menu="menu" @changeCurrentButton="changeCurrentButton" />
    </app-container>
  </div>
</template>
