<template>
	<div class="page">
		<el-form :inline="true" v-if="searchVisible" class="query-form m-b-10" ref="searchForm" :model="searchForm"
			@keyup.enter.native="refreshList()" @submit.native.prevent>
			<el-form-item label="姓名" prop="customerName">
				<el-input v-model="searchForm.customerName" placeholder="请输入姓名" clearable></el-input>
			</el-form-item>
			<el-form-item label="手机号" prop="mobile">
				<el-input v-model="searchForm.mobile" placeholder="请输入手机号" clearable></el-input>
			</el-form-item>
			<el-form-item label="公司名称" prop="companyName">
				<el-input v-model="searchForm.companyName" placeholder="请输入公司名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="挂账状态" prop="creditStatus">
				<el-select v-model="searchForm.creditStatus" placeholder="请选择挂账状态" clearable style="width: 140px">
					<el-option v-for="item in $dictUtils.getDictList('credit_status')" :key="item.value"
						:label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="refreshList()" icon="el-icon-search">查询</el-button>
				<el-button @click="resetSearch()" icon="el-icon-refresh-right">重置</el-button>
			</el-form-item>
		</el-form>

		<div class="jp-table top">
			<vxe-toolbar :refresh="{ query: refreshList }" custom>
				<template #buttons>
					<el-button v-if="hasPermission('psi:creditCustomer:add')" type="primary" icon="el-icon-plus"
						@click="add()">新建</el-button>
					<el-button v-if="hasPermission('psi:creditCustomer:del')" type="danger" icon="el-icon-delete"
						@click="del()"
						:disabled="$refs.creditCustomerTable && $refs.creditCustomerTable.getCheckboxRecords().length === 0"
						plain>删除</el-button>
				</template>
				<template #tools>
					<vxe-button text type="primary" :title="searchVisible ? '收起检索' : '展开检索'" icon="vxe-icon-search"
						class="tool-btn" @click="searchVisible = !searchVisible"></vxe-button>
				</template>
			</vxe-toolbar>
			<div style="height: calc(100% - 90px)">
				<vxe-table border="inner" auto-resize resizable height="auto" :loading="loading"
					ref="creditCustomerTable" show-header-overflow show-overflow highlight-hover-row :menu-config="{}"
					:data="dataList" :checkbox-config="{}">
					<vxe-column type="seq" width="60" title="序号"></vxe-column>
					<vxe-column type="checkbox" width="60"></vxe-column>
					<vxe-column min-width="130" align="center" title="姓名" field="customerName">
						<template #default="scope">
							<el-link type="primary" :underline="false" v-if="hasPermission('psi:creditCustomer:view')"
								@click="view(scope.row.id)">{{ scope.row.customerName }}</el-link>
							<span v-else>{{ scope.row.customerName }}</span>
						</template>
					</vxe-column>
					<vxe-column min-width="130" align="center" title="手机号" field="mobile"></vxe-column>
					<vxe-column min-width="180" align="center" title="公司名称" field="companyName"></vxe-column>
					<vxe-column width="110" align="center" title="挂账状态" field="creditStatus">
						<template #default="scope">
							<el-tag :type="getStatusTagType(scope.row.creditStatus)">{{
								getStatusText(scope.row.creditStatus) }}</el-tag>
						</template>
					</vxe-column>
					<vxe-column width="130" align="right" title="累计欠款金额" field="totalArrearsAmount">
						<template #default="scope">{{ formatMoney(scope.row.totalArrearsAmount) }}</template>
					</vxe-column>
					<vxe-column width="120" align="center" title="未结账单数" field="unsettledBillCount"></vxe-column>
					<vxe-column min-width="170" align="center" title="首次挂账时间" field="firstCreditTime"></vxe-column>
					<vxe-column min-width="170" align="center" title="最后消费时间" field="lastConsumeTime"></vxe-column>
					<vxe-column min-width="170" align="center" title="审核状态" field="status">
						<template #default="scope">
							<el-button effect="dark"
								:type="$dictUtils.getDictLabel('cw_status_flag', scope.row.status, '')">
								{{ $dictUtils.getDictLabel('cw_status', scope.row.status, '未发起') }}
							</el-button>
						</template>
					</vxe-column>
					<vxe-column min-width="120" align="center" title="录入人" field="createName"></vxe-column>
					<vxe-column min-width="120" align="center" title="审核人" field="auditorName"></vxe-column>
					<vxe-column title="操作" width="250px" fixed="right" align="center">
						<template #default="scope">
							<el-button v-if="hasPermission('psi:creditCustomer:edit')" text type="primary" size="small"
								@click="edit(scope.row.id)">修改</el-button>
							<el-dropdown v-if="hasPermission('psi:creditCustomer:edit')" trigger="click"
								@command="handleStatusCommand(scope.row, $event)">
								<el-button text type="primary" size="small">状态<i
										class="el-icon-arrow-down el-icon--right"></i></el-button>
								<template #dropdown>
									<el-dropdown-menu>
										<el-dropdown-item v-for="item in $dictUtils.getDictList('credit_status')"
											:key="item.value" :command="item.value"
											:disabled="scope.row.creditStatus === item.value">{{ item.label
											}}</el-dropdown-item>
									</el-dropdown-menu>
								</template>
							</el-dropdown>
							<el-button v-if="hasPermission('psi:creditCustomer:del')" text type="primary" size="small"
								@click="del(scope.row.id)">删除</el-button>
						</template>
					</vxe-column>
				</vxe-table>
				<vxe-pager background :current-page="tablePage.currentPage" :page-size="tablePage.pageSize"
					:total="tablePage.total" :page-sizes="[10, 20, 100, 1000, { label: '全量数据', value: 1000000 }]"
					:layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
					@page-change="currentChangeHandle">
				</vxe-pager>
			</div>
		</div>
		<CreditCustomerForm ref="creditCustomerForm" @refreshList="refreshList"></CreditCustomerForm>
	</div>
</template>

<script>
import CreditCustomerService from '@/api/psi/CreditCustomerService'
import CreditCustomerForm from './CreditCustomerForm'
import taskService from '@/api/flowable/taskService'
import processService from '@/api/flowable/processService'
import pick from 'lodash.pick'

const CREDIT_CUSTOMER_PROCESS_NAME = '景聚庭-新增挂账人'
const CREDIT_CUSTOMER_FORM_URL = '/psiManagement/dishManage/creditCustomer/CreditCustomerApproval'
export default {
	data() {
		return {
			searchVisible: true,
			searchForm: {
				customerName: '',
				mobile: '',
				companyName: '',
				creditStatus: ''
			},
			dataList: [],
			tablePage: {
				total: 0,
				currentPage: 1,
				pageSize: 10,
				orders: []
			},
			loading: false,
			processDefinitionAuditId: '',
			procDefAuditKey: ''
		}
	},
	creditCustomerService: null,
	created() {
		this.creditCustomerService = new CreditCustomerService()
	},
	components: {
		CreditCustomerForm
	},
	computed: {
		userName() {
			return this.$store.state.user.name
		}
	},
	mounted() {
		this.refreshList()
	},
	activated() {
		this.refreshList()
	},
	methods: {
		add() {
			this.loadProcessDefinition().then(() => {
				if (this.commonJS.isEmpty(this.processDefinitionAuditId)) {
					this.$message.error(`未找到流程【${CREDIT_CUSTOMER_PROCESS_NAME}】，请先配置流程`)
					return
				}
				const tabTitle = `发起流程【${CREDIT_CUSTOMER_PROCESS_NAME}】`
				const processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了[${CREDIT_CUSTOMER_PROCESS_NAME}]`
				taskService.getTaskDef({
					procDefId: this.processDefinitionAuditId,
					status: 'startAndClose'
				}).then((data) => {
					this.$router.push({
						path: '/flowable/task/TaskForm',
						query: {
							...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
							procDefId: this.processDefinitionAuditId,
							procDefKey: this.procDefAuditKey,
							status: 'startAndClose',
							title: tabTitle,
							formType: '2',
							formUrl: CREDIT_CUSTOMER_FORM_URL,
							formTitle: processTitle,
							businessId: 'false',
							isShow: false,
							routePath: this.$route.path
						}
					})
				})
			})
		},
		edit(id) {
			this.$refs.creditCustomerForm.init('edit', id)
		},
		view(id) {
			this.$refs.creditCustomerForm.init('view', id)
		},
		refreshList() {
			this.loadProcessDefinition()
			this.loading = true
			this.creditCustomerService.list({
				'current': this.tablePage.currentPage,
				'size': this.tablePage.pageSize,
				'orders': this.tablePage.orders,
				...this.searchForm
			}).then((data) => {
				this.dataList = data.records
				this.tablePage.total = data.total
				this.loading = false
			}).catch(() => {
				this.loading = false
			})
		},
		loadProcessDefinition() {
			return processService.getByName(CREDIT_CUSTOMER_PROCESS_NAME).then((data) => {
				if (!this.commonJS.isEmpty(data.id)) {
					this.processDefinitionAuditId = data.id
					this.procDefAuditKey = data.key
				}
			})
		},
		currentChangeHandle({ currentPage, pageSize }) {
			this.tablePage.currentPage = currentPage
			this.tablePage.pageSize = pageSize
			this.refreshList()
		},
		handleStatusCommand(row, creditStatus) {
			if (row.creditStatus === creditStatus) {
				return
			}
			this.$confirm(`确定将挂账状态修改为【${this.getStatusText(creditStatus)}】吗？`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.creditCustomerService.changeStatus(row.id, creditStatus).then((data) => {
					this.$message.success(data)
					this.refreshList()
				})
			})
		},
		del(id) {
			let ids = id || this.$refs.creditCustomerTable.getCheckboxRecords().map(item => {
				return item.id
			}).join(',')
			this.$confirm(`确定删除所选项吗？`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.loading = true
				this.creditCustomerService.delete(ids).then((data) => {
					this.$message.success(data)
					this.refreshList()
					this.loading = false
				}).catch(() => {
					this.loading = false
				})
			})
		},
		resetSearch() {
			this.$refs.searchForm.resetFields()
			this.tablePage.currentPage = 1
			this.refreshList()
		},
		getStatusText(status) {
			return this.$dictUtils.getDictLabel('credit_status', status, "正常挂账")
		},
		getStatusTagType(status) {
			return {
				'1': 'success',
				'2': 'warning',
				'3': 'danger'
			}[status] || 'success'
		},
		formatMoney(value) {
			return Number(value || 0).toFixed(2)
		}
	}
}
</script>
