<script setup lang="ts">
import {ref, reactive, defineAsyncComponent, onMounted, nextTick} from 'vue'
import { useRouter } from 'vue-router'
import { fnMd5 } from '@/utils/common'
import TableBase from '@/components/TableBase/index.vue'
import { Edit, Delete, Finished, View ,Check } from '@element-plus/icons-vue'
import type { ColumnProps } from '@/components/TableBase/interface/index'
import { percentage_List, percentage_User_List,percentage_del,percentage_Excel } from '@/api/percentage/index'
import { useTablePublic, options2 } from '@/hooks/useTablePublic'
import {ElMessage} from "element-plus";
import {percentage_Approval, percentage_Remit} from "@/api/mypercentage";

const router = useRouter()
const TableRef = ref<InstanceType<typeof TableBase> | null>(null)
const { globalStore, searchOnTableList, updateOnTableList } = useTablePublic()

const PercentageDetail1Ref = ref<InstanceType<typeof PercentageDetail1> | null>(null)
const PercentageDetail1 = defineAsyncComponent({
  loader: () => import(/*webpackChunkName: 'ContractForm'*/ './PercentageDetail1.vue'),
  delay: 500,
  timeout: 3000,
  suspensible: true
})
const multipleSelection = ref<any[]>([])
const columns: ColumnProps[] = [
  { type: 'selection', width: '44px', fixed: 'left'},
  { type: 'index', label: '序号', width: 80 },
  { prop: 'T_verifyCompany_name', label: '公司名称', name: 'T_verifyCompany_name'},
  { prop: 'T_verifyCompany_State', label: '回款状态', name: 'T_verifyCompany_State'},
  { prop: 'T_recoveries_time', label: '回款时间', name: 'T_recoveries_time',width: 115},
  { prop: 'T_task_id', label: '任务编号'},
  { prop: 'T_task_name', label: '任务名称'},
  { prop: 'T_reporting_pass_time', label: '统计日期',width: 115},
  { prop: 'T_type', label: '提成类型', name: 'T_type' },
  { prop: 'T_device_type', label: '设备类型'},
  { prop: 'T_verify_type', label: '验证类型'},
  { prop: 'T_uuid_name', label: '提成人员' },
  { prop: 'T_money', label: '提成金额' },
  { prop: 'T_approval_money', label: '审批金额' },
  { prop: 'T_State', label: '状态', name: 'T_State' },
  { prop: 'operation', label: '操作', width: 280, fixed: 'right' }
]

const processContract = (type: string, row?: any) => {
  // ContForm.showTable = false
  // router.push({ name: 'PercentageDetail1', params: { id, type: fnMd5('contract'),titles:titles}})
  // PercentageDetail1Ref.value?.VerifyltemApi()
  PercentageDetail1Ref.value?.openDrawer(type, row)
}
const processContractxiang = (id: string, titles: string) => {
  router.push({ name: 'PercentageDetail', params: { id, type: fnMd5('contract'), titles: titles } })
}
// 搜索
const T_date = ref<string[]>([])
const T_reporting_date = ref<string[]>([])
const initParam = reactive({
  User_tokey: globalStore.GET_User_tokey,
  T_name: '',
  T_state: '',
  T_uuid: '',
  T_end_date: '',
  T_start_date: '',
  T_reporting_start_time: '',
  T_reporting_end_time: ''
})
const loading = ref(false)
const centerDialogVisible = ref(false)

const searchHandle = () => {
	initParam.T_end_date = T_date.value ? T_date.value[1] : ''
	initParam.T_start_date = T_date.value ? T_date.value[0] : ''
	initParam.T_reporting_start_time = T_reporting_date.value ? T_reporting_date.value[0] : ''
	initParam.T_reporting_end_time = T_reporting_date.value ? T_reporting_date.value[1] : ''
	TableRef.value?.searchTable()
}

// 导出
const exportPercentageExcel = async () => {
	initParam.T_end_date = T_date.value ? T_date.value[1] : ''
	initParam.T_start_date = T_date.value ? T_date.value[0] : ''
	initParam.T_reporting_start_time = T_reporting_date.value ? T_reporting_date.value[0] : ''
	initParam.T_reporting_end_time = T_reporting_date.value ? T_reporting_date.value[1] : ''
	TableRef.value?.searchTable()
	const res: any = await percentage_Excel(initParam)
	if (res.Code === 200) {
		window.open(res.Data)
	}
}

interface ListItem {
  value: string
  label: string
}
const list = ref<ListItem[]>([])
const optionsData = ref<ListItem[]>([])
const remoteMethod = async (query: string) => {
  if (query) {
    loading.value = true
    setTimeout(() => {
      loading.value = false
      optionsData.value = list.value.filter((item: any) => {
        return item.label.toLowerCase().includes(query.toLowerCase())
      })
    }, 200)
  } else {
    optionsData.value = list.value
  }
}
const click2 = async () => { optionsData.value = list.value }
onMounted(async () => {
  const result: any = await percentage_User_List({})
	let arr =  []
	if (result?.Data !== null) {
		arr = result.Data.Data
	}

  list.value = arr.map((item: any) => {
    return { value: item.T_uuid, label: item.T_name }
  })
})

const ContractFormRef = ref<InstanceType<typeof ContractForm> | null>(null)
const ContForm = reactive({
  id: null,
  showTable: true
})
const ContractForm = defineAsyncComponent({
  loader: () => import(/*webpackChunkName: 'ContractForm'*/ './PercentageForm.vue'),
  delay: 500,
  timeout: 3000,
  suspensible: true
})

const setId = ref()
const subDelectfun = async (id: any,sub: any) => {
  if (sub=='sub') {//提交
    const reslut:any = await percentage_del({T_id: setId.value})
    console.log('res',reslut)
    if(reslut.Code==200){TableRef.value?.getTableList();centerDialogVisible.value = false}
  } else {//显示
    centerDialogVisible.value = true
    setId.value = id
  }
  console.log('确定删除', id,sub)
}

//打款
const SubmitRemit = async (row: any) => {
	const reslut: any = await percentage_Remit({T_id: row.Id})
	console.log('打款', reslut, row)
	if (reslut.Code == 200 && reslut.Msg == 'ok!') {
		searchOnTableList(TableRef.value)
		ElMessage.success(reslut.Msg)
	}
}
// 保存选中的数据id,row-key就是要指定一个key标识这一行的数据
const getRowKey = (row: any) => {
	return row.Id
}
const handleSelectionChange = (val: any[]) => {
	multipleSelection.value = val
	console.log(multipleSelection.value)
}

// 批量提交打款
const batchSubmitRemit = async () => {
	if (multipleSelection.value.length === 0) {
		ElMessage.warning('请选择提成!!!')
		return
	}

	for await (let item of multipleSelection.value) {
		percentage_Remit({ T_id: item.Id })
	}

	ElMessage.success('打款成功!!!')
	nextTick(() => {
		multipleSelection.value = []
		searchOnTableList(TableRef.value)
		TableRef.value?.clearSelection()
	})
}

// 批量提审核
const batchSubmitApproval = async () => {
	if (multipleSelection.value.length === 0) {
		ElMessage.warning('请选择提成!!!')
		return
	}

	for await (let item of multipleSelection.value) {
		percentage_Approval({ T_id: item.Id,  T_state: 2 })
	}

	ElMessage.success('审核通过!!!')
	nextTick(() => {
		multipleSelection.value = []
		searchOnTableList(TableRef.value)
		TableRef.value?.clearSelection()
	})
}

</script>

<template>
  <div class="contract">
    <TableBase ref="TableRef" :columns="columns" :requestApi="percentage_List" :initParam="initParam"
			   selectId="Id"
			   :getRowKey="getRowKey"
			   :selection-change="handleSelectionChange"
	>
      <template #table-header>
        <div class="input-suffix">
          <el-row :gutter="20" style="margin-bottom: 0">
            <el-col :xl="5" :lg="5" :md="5" style="display: flex">
				  <span class="inline-flex items-center">回款日期：</span>
				  <el-date-picker
					  v-model="T_date"
					  type="daterange"
					  range-separator="~"
					  start-placeholder="开始时间"
					  end-placeholder="结束时间"
					  format="YYYY-MM-DD"
					  value-format="YYYY-MM-DD"
				  />
			  </el-col>
			<el-col :xl="5" :lg="5" :md="5" style="display: flex">
				  <span class="inline-flex items-center">统计日期：</span>
				  <el-date-picker
					  v-model="T_reporting_date"
					  type="daterange"
					  range-separator="~"
					  start-placeholder="开始时间"
					  end-placeholder="结束时间"
					  format="YYYY-MM-DD"
					  value-format="YYYY-MM-DD"
				  />
			  </el-col>
            <el-col :xl="4" :lg="4"  :md="4">
              <span class="inline-flex items-center">关键字：</span>
              <el-input v-model="initParam.T_name" type="text" style="width: 150px;" placeholder="按任务编号、公司名称搜索" clearable
                @change="searchOnTableList(TableRef)" />
            </el-col>
            <el-col :xl="4" :lg="4"  :md="4">
              <span class="inline-flex items-center">提成人：</span>
              <el-select v-model="initParam.T_uuid" filterable remote reserve-keyword placeholder="提成人"
                :remote-method="remoteMethod" :loading="loading" @click="click2" clearable style="width: 150px;">
                <el-option v-for="item in optionsData" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-col>
            <el-col :xl="5" :lg="5"  :md="5">
              <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 options2" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
				<el-button type="primary" @click="searchHandle">搜索</el-button>
			</el-col>
			<el-col :xl="15" :lg="15" :md="15" style="margin-top: 15px">
			  <el-button type="warning" @click="batchSubmitApproval">批量审核通过</el-button>
			  <el-button type="success" @click="batchSubmitRemit">批量打款</el-button>
			  <el-button type="primary" @click="exportPercentageExcel">导出表格</el-button>
			</el-col>

          </el-row>
        </div>
      </template>
      <template #T_type="{ row }">
        <el-tag v-if="row.T_type === 1" type="success" effect="dark"> 验证实施 </el-tag>
        <el-tag v-if="row.T_type === 2" type="" effect="dark"> 报告编写 </el-tag>
      </template>
      <template #T_State="{ row }">
        <el-tag v-if="row.T_State === 1" type="info" effect="dark"> 待审核 </el-tag>
        <el-tag v-if="row.T_State === 2" type="success" effect="dark"> 审核通过 </el-tag>
        <el-tag v-if="row.T_State === 3" type="danger" effect="dark"> 审核不通过 </el-tag>
        <el-tag v-if="row.T_State === 4" type="info" effect="dark"> 部分打款 </el-tag>
        <el-tag v-if="row.T_State === 5" type="" effect="dark"> 已打款 </el-tag>
      </template>
      <template #T_verifyCompany_name="{ row }">
        {{row.T_verifyCompany.T_name}}
      </template>
      <template #T_verifyCompany_State="{ row }">
        <el-tag v-if="row.T_verifyCompany.T_State === 1" type="info" effect="dark"> 未回款</el-tag>
        <el-tag v-if="row.T_verifyCompany.T_State === 2" type="success" effect="dark"> 已回款</el-tag>
      </template>
		<template #T_recoveries_time="{ row }">
			{{row.T_verifyCompany.T_recoveries_time}}
		</template>
      <template #right="{ row }">
        <el-button link type="warning" :disabled="![1, 3].includes(row.T_State)" size="small" :icon="Finished"
          @click="processContract('审核', row)">审核</el-button>
        <el-button link type="primary" size="small" :disabled="![2].includes(row.T_State)" :icon="Check"
					 @click="SubmitRemit(row)">打款
        </el-button>
        <el-button link type="success" size="small" :icon="View"
          @click="processContractxiang(row.Id, '详情')">详情</el-button>
        <el-button link type="danger" size="small" :icon="View" @click="subDelectfun(row.Id,'show')">删除</el-button>
      </template>
    </TableBase>
    <ContractForm ref="ContractFormRef" :ContForm="ContForm" @onTableList="updateOnTableList(TableRef)" />
    <PercentageDetail1 ref="PercentageDetail1Ref" @onTableList="updateOnTableList(TableRef)" />
    <el-dialog v-model="centerDialogVisible" title="提示" width="30%" center>
      <span style="text-align: center;display: block;">删除操作，是否删除？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="subDelectfun('','sub')">删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
@import '@/styles/var.scss';

.contract {
  @include f-direction;

  :deep(.el-drawer__header) {
    margin-bottom: 0;
  }

  .input-suffix {
    width: 100%;

    .inline-flex {
      white-space: nowrap;
    }

    .btn {
      display: flex;
      justify-content: end;
    }

    .w-50 {
      width: 12.5rem;
    }
  }
}
</style>
