<template>
	<cl-crud :ref="setRefs('crud')" @load="onLoad">
		<el-row type="flex">
			<cl-refresh-btn />
			<cl-add-btn>新建任务</cl-add-btn>
			<!-- <cl-multi-delete-btn /> -->
			<cl-flex1 />
			<!-- <cl-search-key
				field="id"
				:field-list="[
					{
						label: '任务id',
						value: 'id'
					}
				]"
			></cl-search-key> -->
			<demo-adv-search />
			<!-- <cl-adv-search :items="items" :op-list="opList"></cl-adv-search> -->
		</el-row>

		<el-row>
			<cl-table v-bind="table">
				<template #column-target_new_low="{ scope }">
					<span v-if="scope.row.target_new_low != scope.row.target_new_high">{{ scope.row.target_new_low
					}}&nbsp;-&nbsp;{{
		scope.row.target_new_high
}}</span>
					<span v-if="scope.row.target_new_low == scope.row.target_new_high">{{
							scope.row.target_new_low
					}}</span>
				</template>
				<template #column-target_pay_low="{ scope }">
					<span v-if="scope.row.target_pay_low != scope.row.target_pay_high">{{ scope.row.target_pay_low
					}}&nbsp;-&nbsp;{{
		scope.row.target_pay_high
}}</span>
					<span v-if="scope.row.target_pay_low == scope.row.target_pay_high">{{
							scope.row.target_pay_low
					}}</span>
				</template>
				<template #column-target_active_low="{ scope }">
					<span v-if="scope.row.target_active_low != scope.row.target_active_high">{{
							scope.row.target_active_low
					}}&nbsp;-&nbsp;{{
		scope.row.target_active_high
}}</span>
					<span v-if="scope.row.target_active_low == scope.row.target_active_high">{{
							scope.row.target_active_low
					}}</span>
				</template>
				<template #column-unit_price_low="{ scope }">
					<span v-if="scope.row.unit_price_low != scope.row.unit_price_high">{{ scope.row.unit_price_low
					}}&nbsp;-&nbsp;{{
		scope.row.unit_price_high
}}</span>
					<span v-if="scope.row.unit_price_low == scope.row.unit_price_high">{{
							scope.row.unit_price_low
					}}</span>
				</template>
				<template #slot-stop="{ scope }">
					<el-button v-if="scope.row.is_run == 1" type="text" size="mini" @click="switchPage(scope.row)">停止
					</el-button>
					<el-button v-if="scope.row.is_run == 0" type="text" size="mini" @click="startTask(scope.row)">开始
					</el-button>
				</template>
				<template #slot-devices="{ scope }">
					<el-button type="text" size="mini" @click="navTo(scope.row)">设备</el-button>
				</template>
				<template #slot-delete="{ scope }">
					<el-button type="text" size="mini" @click="deleteTask(scope.row)">删除</el-button>
				</template>
				<template #slot-script="{ scope }">
					<el-button type="text" size="mini" @click="navToScript(scope.row)">上传</el-button>
				</template>
				<template #slot-file="{ scope }">
					<el-button type="text" size="mini" @click="navToFile(scope.row)">文件</el-button>
				</template>
			</cl-table>
		</el-row>

		<el-row type="flex">
			<cl-flex1 />
			<cl-pagination />
		</el-row>

		<cl-upsert v-model="form" v-bind="upsert"> </cl-upsert>
		<cl-dialog title="终止任务" v-model="visible">
			<el-form ref="elForm" :model="stopForm" size="medium" label-width="100px">
				<el-form-item label="终止任务名称" prop="name">
					<el-col :span="20">
						<span style="color: red">{{ stopForm.name }}</span>
					</el-col>
				</el-form-item>
				<el-form-item label="终止任务时间" prop="stopTime">
					<el-col :span="6">
						<el-date-picker v-model="stopForm.stopTime" format="YYYY-MM-DD HH:mm:ss" type="datetime"
							:style="{ width: '100%' }" placeholder="请选择日期选择" clearable></el-date-picker>
					</el-col>
				</el-form-item>
				<el-form-item label="终止任务原因" prop="stopRemark">
					<el-col :span="20">
						<el-input v-model="stopForm.stopRemark" type="textarea" placeholder="请输入多行文本"
							:autosize="{ minRows: 2, maxRows: 4 }" :style="{ width: '100%' }"></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="删除相关文件" prop="isDelete">
					<el-col :span="20">
						<el-radio v-model="stopForm.isDelete" label="1">是</el-radio>
						<el-radio v-model="stopForm.isDelete" label="2">否</el-radio>
					</el-col>
				</el-form-item>
				<el-form-item>
					<el-button size="small" @click="visible = false">取消</el-button>
					<el-button type="primary" size="small" @click="stopTask(stopForm)">确定终止</el-button>
				</el-form-item>
			</el-form>
		</cl-dialog>
		<cl-dialog title="任务设备" v-model="deviceVisible">
			<el-table :data="deviceList" border style="width: 100%">
				<el-table-column prop="task_id" label="任务ID" align="center" header-align="center" />
				<el-table-column prop="pc_name" label="电脑编号" align="center" header-align="center" />
				<el-table-column prop="remark" label="备注" align="center" header-align="center" />
				<el-table-column prop="updateTime" label="更新时间" />
				<el-table-column fixed="right" label="操作" width="150" align="center" header-align="center">
					<el-button type="warning" plain size="small" @click="deleteDevice">修改</el-button>
					<el-button type="warning" plain size="small" @click="deleteDevice">删除</el-button>
				</el-table-column>
			</el-table>
		</cl-dialog>
		<el-dialog title="脚本/镜像/文件更新" v-model="scriptVisible" :center="true" :close-on-click-modal="false"
			:close-on-press-escape="false">
			<el-form ref="elForm2" :model="scriptForm" size="medium" label-width="100px">
				<el-form-item label="任务ID" prop="name">
					<el-col :span="11">
						<el-input v-model="scriptForm.id" placeholder="任务ID" disabled></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="任务名称" prop="name">
					<el-col :span="11">
						<el-input v-model="scriptForm.name" placeholder="任务名称" disabled></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="更新时间" prop="updateTime">
					<el-col :span="11">
						<el-date-picker v-model="scriptForm.updateTime" format="YYYY-MM-DD HH:mm:ss" type="datetime"
							disabled :style="{ width: '100%' }" placeholder="请选择日期选择" clearable></el-date-picker>
					</el-col>
				</el-form-item>
				<el-form-item label="文件类型" prop="type">
					<el-col :span="11">
						<el-select v-model="scriptForm.type" placeholder="文件类型" :style="{ width: '100%' }"
							@change="selectChanged(scriptForm)">
							<el-option v-for="item in typeOptions" :key="item.value" :label="item.label"
								:value="item.value" />
						</el-select>
					</el-col>
				</el-form-item>
				<el-form-item label="文件名称" prop="scriptVersion">
					<el-col :span="11">
						<el-input v-model="scriptForm.fileName" placeholder="文件名称,选择文件后自动生成" disabled
							:style="{ width: '100%' }"></el-input>
					</el-col>
				</el-form-item>
				<el-form-item v-if="showVersion" label="更新版本" prop="scriptVersion">
					<el-col :span="11">
						<el-input v-model="scriptForm.scriptVersion" placeholder="版本号" disabled
							:style="{ width: '100%' }"></el-input>
					</el-col>
				</el-form-item>
				<el-form-item v-if="showUpload" label="选择文件" prop="scriptAddress">
					<el-col :span="11">
						<el-upload :limit="1" action="http://upload-z2.qiniup.com" :data="qiniuData" drag
							:disabled="disabledUpload" :show-file-list="false" :http-request="uploadHttpRequest"
							:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
							:on-progress="onProgress">
							<div class="el-default" v-if="!progressFlag">
								<i class="el-icon-upload"></i>
								<div class="el-upload__text">
									将文件拖到此处，或<em> 点击上传 </em>
								</div>
							</div>
							<el-progress type="circle" :percentage="progress" :stroke-width="15"
								style="margin-top: 20px" v-if="progressFlag">
							</el-progress>
						</el-upload>
						<!-- 进度条 -->
						<!-- <el-progress
							v-if="progressFlag"
							:text-inside="true"
							:percentage="progress"
							:stroke-width="15"
							:status="status"
						></el-progress> -->
					</el-col>
				</el-form-item>
				<el-form-item>
					<el-button size="small" @click="cancelUp(scriptForm)">取消上传</el-button>
					<!-- <el-button type="primary" size="small" @click="recordFile(scriptForm)"
						>确定上传</el-button
					> -->
				</el-form-item>
			</el-form>
		</el-dialog>
		<el-dialog title="已上传文件展示" v-model="fileVisible" :center="true" :close-on-click-modal="false"
			:close-on-press-escape="false" width="70%">
			<el-table :data="fileList" border style="width: 100%">
				<el-table-column prop="fileName" label="文件名称" align="left" min-width="150" header-align="left" />
				<el-table-column prop="type" label="文件类型" align="left" min-width="50" header-align="left" />
				<el-table-column prop="fileVersion" label="文件版本" align="left" min-width="50" header-align="left" />
				<el-table-column prop="qiniuAddress" label="下载链接" align="left" min-width="250" header-align="left" />
				<el-table-column prop="qiniuHash" label="七牛HASH" align="left" min-width="150" header-align="left" />
				<el-table-column prop="updateTime" min-width="100" label="上传时间" />
				<el-table-column fixed="right" label="操作" width="80" align="center" header-align="center">
					<template #default="scope">
						<el-button size="small" type="danger" plain @click="deleteFiles(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-dialog>
	</cl-crud>
</template>

<script lang="ts">
import { CrudLoad, Table, Upsert } from "cl-admin-crud-vue3/types";
import { defineComponent, inject, reactive, ref } from "vue";
import AdvSearch from "../components/adv-search.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
import { useRefs } from "/@/core";
// import { useRouter } from "vue-router";
import * as qiniu from "qiniu-js";
// import SparkMD5 from "spark-md5";
// import sha1 from "sha1-file-web";
export default defineComponent({
	name: "game-task",

	components: {
		"demo-adv-search": AdvSearch
	},

	setup() {
		const typeOptions = [
			{
				value: "0",
				label: "游戏.apk"
			},
			{
				value: "1",
				label: "小精灵.apk"
			},
			{
				value: "2",
				label: "Tar包更新.tar"
			},
			{
				value: "3",
				label: "Bat.bat"
			},
			{
				value: "4",
				label: "shell脚本.sh"
			},
			{
				value: "5",
				label: "exe文件.exe"
			},
			{
				value: "6",
				label: "PC精灵.exe"
			},
			{
				value: "7",
				label: "小绵羊.apk"
			},
			{
				value: "8",
				label: "多开王.exe"
			},
			{
				value: "9",
				label: "雷电镜像.ldbk"
			},
			{
				value: "10",
				label: "夜神镜像.npbk"
			},
			{
				value: "11",
				label: "易脚本.dll"
			},
			{
				value: "12",
				label: "钛备份文件.*"
			}
		];
		const service = inject<any>("service");
		// const router = useRouter();
		const { refs, setRefs }: any = useRefs();
		// 表单值
		const form = reactive<any>({
			relevance: 1
		});
		// 表单值
		const stopForm = reactive<any>({
			id: "",
			name: "",
			game_agentId: "",
			stopTime: new Date(),
			stopRemark: "无",
			isDelete: "2"
		});
		const scriptForm = reactive<any>({
			id: "",
			name: "",
			updateTime: "",
			fileName: "",
			type: null,
			scriptVersion: "",
			key: "",
			scriptAddress: "",
			scriptHash: ""
		});
		const showVersion = ref<boolean>(false);
		const showUpload = ref<boolean>(false);
		let deviceList = ref<any[]>([]);
		let fileList = ref<any[]>([]);
		// 是否可见
		const visible = ref<boolean>(false);
		const deviceVisible = ref<boolean>(false);
		const fileVisible = ref<boolean>(false);
		const scriptVisible = ref<boolean>(false);
		const progressFlag = ref<boolean>(false);
		const status = ref<string>("exception");
		const progress = ref<number>(0);
		const cance = ref<boolean>(false);
		const disabledUpload = ref<boolean>(false);
		// 新增、编辑配置
		const upsert = reactive<Upsert>({
			width: "800px",

			items: [
				{
					prop: "id",
					label: "任务ID",
					span: 8,
					component: {
						name: "el-input",
						props: {
							placeholder: "请填写任务ID"
						}
					},
					rules: {
						required: true,
						message: "任务ID不能为空"
					}
				},
				{
					prop: "task_name",
					label: "任务名称",
					span: 8,
					component: {
						name: "el-input",
						props: {
							placeholder: "任务名称"
						}
					},
					rules: {
						required: true,
						message: "任务名称不能为空"
					}
				},
				{
					prop: "directorId",
					label: "负责人",
					span: 8,
					component: {
						name: "shuyouGameDirectorselect",
						props: {
							placeholder: "负责人"
						}
					},
					rules: {
						required: true,
						message: "负责人不能为空"
					}
				},
				{
					prop: "is_repeat",
					label: "重复游戏",
					value: 0,
					span: 8,
					component: {
						name: "el-radio-group",
						props: {
							disabled: true
						},
						options: [
							{
								label: "是",
								value: 1
							},
							{
								label: "否",
								value: 0
							}
						]
					}
				},
				{
					prop: "unit_price_low",
					label: "单价下限",
					span: 8,
					value: 6.0,
					component: {
						name: "el-input",
						props: {
							placeholder: "付费单价下限"
						}
					}
				},
				{
					prop: "unit_price_high",
					label: "单价上限",
					span: 8,
					value: 6.0,
					component: {
						name: "el-input",
						props: {
							placeholder: "付费单价上限"
						}
					}
				},
				{
					prop: "new_retained",
					label: "重要参数",
					value: 0,
					span: 20,
					component: {
						name: "el-radio-group",
						options: [
							{
								label: "用新增做付费,会同步至机房",
								value: 1
							},
							{
								label: "用留存做付费,会同步至机房",
								value: 2
							}
						]
					},
					rules: {
						required: true,
						message: "此参数必须选择"
					}
				},
				{
					type: "tabs",
					props: {
						labels: [
							{
								label: "基本信息",
								value: "base"
							},
							{
								label: "数优目标",
								value: "target"
							}
						]
					}
				},
				{
					prop: "gameIdList",
					label: "游戏名称",
					span: 24,
					value: [],
					group: "base",
					component: {
						name: "shuyouGameListSelect",
						props: {
							props: {
								"multiple-limit": 1
							}
						}
					},
					rules: {
						required: true,
						message: "游戏名称不能为空"
					}
				},
				{
					prop: "new_date",
					label: "开始日期",
					span: 8,
					group: "base",
					value: dayjs(new Date()).format("YYYY-MM-DD"),
					component: {
						name: "el-date-picker",
						props: {
							type: "date",
							placeholder: "选择日期",
							format: "YYYY-MM-DD",
							valueFormat: "YYYY-MM-DD"
						}
					},
					rules: {
						required: true,
						message: "日期不能为空"
					}
				},
				{
					prop: "game_agentId",
					label: "游戏端口",
					span: 8,
					group: "base",
					component: {
						name: "shuyouGameAgentselect",
						props: {
							placeholder: "游戏端口"
						}
					},
					rules: {
						required: true,
						message: "负责人不能为空"
					}
				},
				{
					prop: "account_typeId",
					label: "账号类型",
					span: 8,
					group: "base",
					component: {
						name: "shuyouAccountTypeselect",
						props: {
							placeholder: "账号类型"
						}
					},
					rules: {
						required: true,
						message: "账号类型不能为空"
					}
				},
				{
					prop: "login_modeId",
					label: "登录方式",
					span: 8,
					group: "base",
					component: {
						name: "shuyouLoModeselect",
						props: {
							placeholder: "登录方式"
						}
					},
					rules: {
						required: true,
						message: "登录方式不能为空"
					}
				},
				{
					prop: "xmy_id",
					label: "小绵羊id",
					span: 8,
					group: "base",
					hidden: ({ scope }: any) => {
						return scope.login_modeId != 1;
					},
					component: {
						name: "el-input",
						props: {
							placeholder: "小绵羊id"
						}
					},
					rules: {
						required: true,
						message: "账号类型不能为空"
					}
				},
				{
					prop: "qq_channel",
					label: "腾讯渠道",
					span: 8,
					group: "base",
					hidden: ({ scope }: any) => {
						return (
							scope.login_modeId != 3 &&
							scope.login_modeId != 5 &&
							scope.login_modeId != 6
						);
					},
					component: {
						name: "el-input",
						props: {
							placeholder: "腾讯渠道id"
						}
					},
					rules: {
						required: true,
						message: "腾讯渠道不能为空"
					}
				},
				{
					prop: "qq_id",
					label: "腾讯游戏id",
					span: 8,
					group: "base",
					hidden: ({ scope }: any) => {
						return (
							scope.login_modeId != 3 &&
							scope.login_modeId != 5 &&
							scope.login_modeId != 6
						);
					},
					component: {
						name: "el-input",
						props: {
							placeholder: "腾讯游戏id"
						}
					}
				},
				{
					prop: "mz_channel",
					label: "魅族渠道",
					span: 8,
					group: "base",
					hidden: ({ scope }: any) => {
						return (
							scope.game_agentId != 5 && scope.login_modeId != 2
						);
					},
					component: {
						name: "el-input",
						props: {
							placeholder: "魅族游戏渠道"
						}
					},
					rules: {
						required: true,
						message: "游戏渠道不能为空"
					}
				},
				{
					prop: "mz_id",
					label: "魅族游戏id",
					span: 8,
					group: "base",
					hidden: ({ scope }: any) => {
						return (
							scope.game_agentId != 5 && scope.login_modeId != 2
						);
					},
					component: {
						name: "el-input",
						props: {
							placeholder: "魅族游戏id"
						}
					}
				},
				{
					prop: "download",
					label: "下载链接",
					span: 24,
					group: "base",
					component: {
						name: "el-input",
						props: {
							placeholder: "请填写下载链接",
							type: "textarea",
							rows: 3
						}
					}
				},
				{
					prop: "remark",
					label: "任务备注",
					span: 24,
					group: "base",
					component: {
						name: "el-input",
						props: {
							placeholder: "请填写备注",
							type: "textarea",
							rows: 3
						}
					}
				},
				// {
				// 	prop: "is_run",
				// 	label: "是否执行",
				// 	value: 1,
				// 	group: "base",
				// 	component: {
				// 		name: "el-radio-group",
				// 		options: [
				// 			{
				// 				label: "开启",
				// 				value: 1
				// 			},
				// 			{
				// 				label: "关闭",
				// 				value: 0
				// 			}
				// 		]
				// 	}
				// },
				// {
				// 	label: "终止时间",
				// 	prop: "stopTime",
				// 	value: "2099-01-01 00:00:00",
				// 	span: 8,
				// 	group: "base",
				// 	hidden: ({ scope }: any) => {
				// 		return scope.is_run == 1;
				// 	},
				// 	component: {
				// 		name: "el-date-picker",
				// 		props: {
				// 			type: "datetime",
				// 			placeholder: "选择日期"
				// 		}
				// 	},
				// 	rules: {
				// 		required: true,
				// 		message: "日期不能为空"
				// 	}
				// },
				// {
				// 	prop: "stopRemark",
				// 	label: "终止原因",
				// 	span: 24,
				// 	group: "base",
				// 	hidden: ({ scope }: any) => {
				// 		return scope.is_run == 1;
				// 	},
				// 	component: {
				// 		name: "el-input",
				// 		props: {
				// 			placeholder: "请填写终止任务的原因",
				// 			type: "textarea",
				// 			rows: 2
				// 		}
				// 	}
				// },
				{
					prop: "target_new_low",
					label: "新增下限",
					span: 6,
					group: "target",
					component: {
						name: "el-input",
						props: {
							placeholder: "新增下限"
						}
					}
				},
				{
					prop: "target_new_high",
					label: "新增上限",
					span: 6,
					group: "target",
					component: {
						name: "el-input",
						props: {
							placeholder: "新增上限"
						}
					}
				},
				{
					prop: "target_pay_low",
					label: "付费下限",
					span: 6,
					value: 0,
					group: "target",
					component: {
						name: "el-input",
						props: {
							placeholder: "付费下限"
						}
					}
				},
				{
					prop: "target_pay_high",
					label: "付费上限",
					span: 6,
					value: 0,
					group: "target",
					component: {
						name: "el-input",
						props: {
							placeholder: "付费上限"
						}
					}
				},
				{
					prop: "target_active_low",
					label: "活跃下限",
					span: 6,
					value: 1,
					group: "target",
					component: {
						name: "el-input",
						props: {
							placeholder: "活跃下限"
						}
					}
				},
				{
					prop: "target_active_high",
					label: "活跃上限",
					span: 6,
					value: 1,
					group: "target",
					component: {
						name: "el-input",
						props: {
							placeholder: "活跃上限"
						}
					}
				},
				{
					label: "次留比例",
					prop: "lc_two_ratio",
					value: 0.5,
					span: 6,
					group: "target",
					component: {
						name: "el-input-number",
						props: {
							precision: "2",
							step: "0.05",
							min: "0",
							max: "1"
						}
					},
					rules: {
						required: true,
						message: "次留比例不能为空"
					}
				},
				{
					label: "3留比例",
					prop: "lc_three_ratio",
					value: 0.45,
					span: 6,
					group: "target",
					component: {
						name: "el-input-number",
						props: {
							precision: "2",
							step: "0.05",
							min: "0",
							max: "1"
						}
					},
					rules: {
						required: true,
						message: "3留比例不能为空"
					}
				},
				{
					label: "4留比例",
					prop: "lc_four_ratio",
					value: 0.4,
					span: 6,
					group: "target",
					component: {
						name: "el-input-number",
						props: {
							precision: "2",
							step: "0.05",
							min: "0",
							max: "1"
						}
					},
					rules: {
						required: true,
						message: "4留比例不能为空"
					}
				},
				{
					label: "5留比例",
					prop: "lc_five_ratio",
					value: 0.35,
					span: 6,
					group: "target",
					component: {
						name: "el-input-number",
						props: {
							precision: "2",
							step: "0.05",
							min: "0",
							max: "1"
						}
					},
					rules: {
						required: true,
						message: "5留比例不能为空"
					}
				},
				{
					label: "6留比例",
					prop: "lc_six_ratio",
					value: 0.3,
					span: 6,
					group: "target",
					component: {
						name: "el-input-number",
						props: {
							precision: "2",
							step: "0.05",
							min: "0",
							max: "1"
						}
					},
					rules: {
						required: true,
						message: "6留比例不能为空"
					}
				},
				{
					label: "7留比例",
					prop: "lc_seven_ratio",
					value: 0.25,
					span: 6,
					group: "target",
					component: {
						name: "el-input-number",
						props: {
							precision: "2",
							step: "0.05",
							min: "0",
							max: "1"
						}
					},
					rules: {
						required: true,
						message: "7留比例不能为空"
					}
				},
				{
					label: "8留比例",
					prop: "lc_eight_ratio",
					value: 0.2,
					span: 6,
					group: "target",
					component: {
						name: "el-input-number",
						props: {
							precision: "2",
							step: "0.05",
							min: "0",
							max: "1"
						}
					},
					rules: {
						required: true,
						message: "8留比例不能为空"
					}
				},
				{
					label: "15留比例",
					prop: "lc_fifteen_ratio",
					value: 0.1,
					span: 6,
					group: "target",
					component: {
						name: "el-input-number",
						props: {
							precision: "2",
							step: "0.05",
							min: "0",
							max: "1"
						}
					},
					rules: {
						required: true,
						message: "15留比例不能为空"
					}
				},
				{
					label: "30留比例",
					prop: "lc_thirty_ratio",
					value: 0.01,
					span: 6,
					group: "target",
					component: {
						name: "el-input-number",
						props: {
							precision: "2",
							step: "0.05",
							min: "0",
							max: "1"
						}
					},
					rules: {
						required: true,
						message: "30留比例不能为空"
					}
				}
				// {
				// 	prop: "status",
				// 	label: "状态",
				// 	value: 1,
				// 	component: {
				// 		name: "el-radio-group",
				// 		options: [
				// 			{
				// 				label: "开启",
				// 				value: 1
				// 			},
				// 			{
				// 				label: "关闭",
				// 				value: 0
				// 			}
				// 		]
				// 	}
				// }
			]
		});

		// 表格配置
		const table = reactive<Table>({
			props: {
				"default-sort": {
					prop: "id",
					order: "ascending"
				}
			},
			columns: [
				{
					type: "selection",
					width: 40
				},
				{
					prop: "id",
					label: "任务id",
					sortable: "custom",
					minWidth: 80
				},
				{
					prop: "task_name",
					label: "任务名",
					minWidth: 200,
					showOverflowTooltip: true,
					headerAlign: "left",
					align: "left"
				},
				{
					prop: "directorName",
					label: "负责人",
					sortable: "custom",
					minWidth: 100
				},
				{
					prop: "gameList",
					label: "游戏名",
					sortable: "custom",
					minWidth: 100
				},
				{
					prop: "game_agentId",
					label: "游戏端口",
					minWidth: 80
				},
				{
					prop: "login_modeId",
					label: "登录方式",
					minWidth: 80
				},
				{
					prop: "target_new_low",
					label: "新增目标",
					minWidth: 100
				},
				{
					prop: "target_pay_low",
					label: "付费目标",
					minWidth: 100
				},
				{
					prop: "target_active_low",
					label: "活跃目标",
					minWidth: 100
				},
				{
					prop: "is_run",
					label: "状态",
					minWidth: 80,
					dict: [
						{
							label: "运行中",
							value: 1,
							type: "success"
						},
						{
							label: "未运行",
							value: 0,
							type: "info"
						}
					]
				},
				{
					prop: "xmy_id",
					label: "小绵羊id",
					minWidth: 80
				},
				{
					prop: "qq_channel",
					label: "腾讯渠道",
					minWidth: 80
				},
				{
					prop: "unit_price_low",
					label: "付费单价",
					minWidth: 80
				},
				{
					prop: "new_date",
					label: "开始日期",
					minWidth: 150
				},
				{
					prop: "stopTime",
					label: "终止时间",
					minWidth: 150
				},
				{
					prop: "stopRemark",
					label: "终止原因",
					minWidth: 150,
					showOverflowTooltip: true
				},
				{
					prop: "account_typeId",
					label: "账号类型",
					minWidth: 100
				},
				{
					prop: "remark",
					label: "备注",
					minWidth: 150
				},
				{
					prop: "createTime",
					label: "创建时间",
					sortable: "custom",
					minWidth: 150
				},
				{
					prop: "updateTime",
					label: "更新时间",
					sortable: "custom",
					minWidth: 150
				},
				{
					type: "op",
					buttons: [
						"edit",
						"slot-stop",
						"slot-devices",
						"slot-delete",
						"slot-script",
						"slot-file"
					],
					width: 180
				}
			]
		});

		// crud 加载
		function onLoad({ ctx, app }: CrudLoad) {
			ctx.service(service.shuyouGameTask).done();
			app.refresh();
		}

		// 调起停止任务弹窗
		async function switchPage(xxx) {
			stopForm.id = xxx.id;
			stopForm.name = xxx.task_name;
			stopForm.game_agentId = xxx.game_agentId;
			stopForm.isDelete = "2";
			// console.log(stopForm);
			if (xxx.is_run == 1) {
				//停止游戏
				visible.value = true;
			}
		}
		// 停止任务
		async function stopTask(aaa) {
			let warn = "";
			if (aaa.isDelete == "1") {
				warn = "此操作将停止该任务，并删除该任务下所有七牛云文件，是否继续？";
			} else {
				warn = "此操作将停止该任务，但保留该任务下所有七牛云文件，是否继续？";
			}
			ElMessageBox.confirm(warn, "提示", {
				type: "warning"
			})
				.then(() => {
					service.shuyouGameTask
						.stopTask(aaa)
						.then((data) => {
							visible.value = false;
							if (data.code == -1) {
								ElMessage.error(data.message);
							} else {
								ElMessage.success(data.message + ",当前任务下文件删除完成");
							}
							//停止任务时删除相关七牛云文件
							if (aaa.isDelete == "1") {
								//
								service.shuyouFileList
									.deleteAllByTaskId({
										task_id: aaa.id
									})
									.then(() => { })
									.catch((err: string) => { });
							}
							// console.log('刷新页面')
							refs.value.crud.refresh();
						})
						.catch((err: string) => {
							ElMessage.error(err);
						});
				})
				.catch(() => null);
		}
		// 开始任务
		async function startTask(xxx) {
			ElMessageBox.confirm("即将开始任务，是否继续？", xxx.id + xxx.task_name, {
				type: "success"
			})
				.then(() => {
					service.shuyouGameTask
						.startTask(xxx)
						.then((data) => {
							if (data.code == -1) {
								ElMessage.error(data.message);
							} else {
								ElMessage.success(data.message);
							}
							refs.value.crud.refresh();
						})
						.catch((err: string) => {
							ElMessage.error(err);
						});
				})
				.catch(() => null);
		}
		//删除任务
		async function deleteTask(xxx) {
			// 此操作将永久删除选中数据，是否继续？
			if (xxx.is_run == 1) {
				ElMessageBox.confirm(
					"此任务仍在运行, 请先停止任务再执行删除!",
					xxx.id + xxx.task_name,
					{
						confirmButtonText: "确认",
						cancelButtonText: "取消",
						type: "warning"
					}
				)
					.then(() => { })
					.catch(() => { });
			} else {
				ElMessageBox.confirm(
					"即将删除此任务, <strong>若今日有<span>目标完成</span>会一并删除</strong>,不建议删除任务, 此操作不可逆, 是否继续?",
					xxx.id + xxx.task_name,
					{
						dangerouslyUseHTMLString: true,
						type: "error"
					}
				)
					.then(() => {
						ElMessageBox.confirm(
							"不建议删除任务, 此操作不可逆, 是否继续?",
							xxx.id + xxx.task_name,
							{
								dangerouslyUseHTMLString: true,
								type: "error"
							}
						)
							.then(() => {
								service.shuyouGameTask
									.deleteById({ id: xxx.id })
									.then((data) => {
										if (data.code == -1) {
											ElMessage.error(data.message);
										} else {
											ElMessage.success(data.message);
										}
										refs.value.crud.refresh();
									})
									.catch((err: string) => {
										ElMessage.error(err);
									});
							})
							.catch(() => null);
					})
					.catch(() => null);
			}
		}
		// 跳转
		async function navTo(rowData) {
			let queryDevice = {
				page: 1,
				size: 20,
				sort: "asc",
				order: "id",
				task_id: rowData.id
			};
			service.shuyouComputerUsage
				.page(queryDevice)
				.then((data) => {
					// console.log(data);
					deviceList.value = data.list;
					deviceVisible.value = true;
				})
				.catch((err: string) => {
					ElMessage.error(err);
				});
		}
		// 跳转
		async function navToScript(xxx) {
			scriptForm.id = xxx.id;
			scriptForm.name = xxx.task_name;
			scriptVisible.value = true;
			showVersion.value = false;
			showUpload.value = false;
			scriptForm.updateTime = new Date();
			scriptForm.fileName = "";
			scriptForm.type = null;
			scriptForm.scriptVersion = "";
			scriptForm.scriptAddress = "";
			progressFlag.value = false;
			await getToken();
			disabledUpload.value = false;
		}
		async function navToFile(aaa) {
			let queryForm = {
				page: 1,
				size: 20,
				sort: "desc",
				order: "updateTime",
				task_id: aaa.id
			};
			service.shuyouFileList
				.page(queryForm)
				.then((data) => {
					fileList.value = data.list;
					fileVisible.value = true;
				})
				.catch((err: string) => {
					ElMessage.error(err);
				});
		}
		//确定上传,记录文件信息在数据库中
		async function recordFile(aaa) {
			const params = {
				task_id: aaa.id,
				updateTime: aaa.updateTime,
				fileVersion: aaa.scriptVersion,
				qiniuAddress: aaa.scriptAddress,
				fileName: aaa.fileName,
				type: aaa.type,
				qiniuHash: aaa.scriptHash,
				qiniuKey: aaa.key
			};
			await service.shuyouFileList
				.add(params)
				.then((data) => {
					scriptVisible.value = false;
					if (data.id) {
						ElMessage.success("文件记录成功!!!");
					} else {
						ElMessage.success("文件记录成功!!!");
					}
				})
				.catch((err: string) => {
					ElMessageBox.alert(err, "提示", {
						confirmButtonText: "关闭"
					});
				});
		}
		async function selectChanged(aaa) {
			//查询该类型对应最新版本号并+1
			await queryVersionByType({
				task_id: aaa.id,
				type: aaa.type
			});
			showVersion.value = true;
			showUpload.value = true;
		}
		//查询该类型对应最新版本号并+1
		async function queryVersionByType(obj) {
			let queryForm = {
				task_id: obj.task_id,
				type: obj.type
			};
			service.shuyouFileList
				.queryVersionByType(queryForm)
				.then((data) => {
					if (data.code == 1) {
						scriptForm.scriptVersion = parseInt(data.fileVersion) + 1;
					}
				})
				.catch((err: string) => {
					ElMessage.error(err);
				});
		}
		let qiniuData = reactive<any>({
			key: "",
			token: "",
			CName: ""
		});
		//获取七牛token
		async function getToken() {
			await service.shuyouFileList
				.getQiniuToken()
				.then((data) => {
					qiniuData.token = data.data.token;
					qiniuData.CName = data.data.CName;
					console.log(qiniuData);
				})
				.catch((err: string) => {
					ElMessageBox.alert(err, "提示", {
						confirmButtonText: "关闭"
					});
				});
		}
		// 取消上传文件
		async function cancelUp(aaa) {
			//中断文件传输
			cance.value = true;
			scriptVisible.value = false;
			var fileUrl = aaa.key;
			const params = {
				fileUrl: fileUrl
			};
			if (fileUrl == "") {
				return;
			}

			//取消上传时从七牛云删除已上传的文件
			await service.shuyouFileList
				.deleteFile(params)
				.then((data) => {
					// content.token = data.data;
					console.log(data.code);
				})
				.catch((err: string) => {
					ElMessageBox.alert(err, "提示", {
						confirmButtonText: "关闭"
					});
				});
		}
		//删除文件
		async function deleteFiles(row) {
			let parm = {
				id: row.id,
				fileUrl: row.qiniuKey
			};

			ElMessageBox.confirm("确定删除文件？", "警告", {
				type: "warning"
			})
				.then(() => {
					service.shuyouFileList
						.deleteFileAndRecord(parm)
						.then((data) => {
							// console.log(data);
							ElMessage.success("删除文件成功!!!");
							fileVisible.value = false;
						})
						.catch((err: string) => {
							ElMessageBox.alert(err, "提示", {
								confirmButtonText: "关闭"
							});
						});
				})
				.catch(() => null);
		}
		//上传前处理
		function beforeAvatarUpload(file) {
			progressFlag.value = false;
			const fileFirst = file.name.substring(0, file.name.lastIndexOf("."));
			const fileLast = file.name.substring(file.name.lastIndexOf(".") + 1);
			//
			const limitType = typeOptions[scriptForm.type].label;
			let isALL = limitType.substring(limitType.lastIndexOf(".") + 1);

			// const isJPG = file.type === "image/jpeg";
			// const isLt50M = file.size / 1024 / 1024 < 2000;
			if (isALL == "*") {
			} else if (fileLast == "" || isALL != fileLast) {
				ElMessageBox.alert("只能上传" + isALL + "格式的文件", "提示", {
					confirmButtonText: "关闭"
				});
				return false;
			}
			let folder =
				"shuyou/" +
				scriptForm.id +
				"/" +
				fileFirst +
				"_" +
				new Date().getTime() +
				"." +
				fileLast;
			scriptForm.fileName = folder;
			qiniuData.key = folder;
			disabledUpload.value = true;
		}

		// async function ReadFileMD5(files) {
		// 	const file = files;
		// 	// const hash = sha1(file);
		// 	async function test(file) {
		// 		//计算SHA1
		// 		const hash = await sha1(file);
		// 		//hash即得到的sha1值
		// 		// console.log(hash);
		// 	}
		// 	test(file);

		// 	//计算MD5
		// 	// const sliceLength = 10;
		// 	// const chunkSize = Math.ceil(file.size / sliceLength);
		// 	// const fileReader = new FileReader();
		// 	// const md5 = new SparkMD5();
		// 	// let index = 0;
		// 	// const loadFile = () => {
		// 	// 	const slice = file.slice(index, index + chunkSize);
		// 	// 	fileReader.readAsBinaryString(slice);
		// 	// };
		// 	// loadFile();
		// 	// fileReader.onload = (e) => {
		// 	// 	md5.appendBinary(e.target.result);
		// 	// 	if (index < file.size) {
		// 	// 		index += chunkSize;
		// 	// 		loadFile();
		// 	// 	} else {
		// 	// 		// md5.end() 就是文件md5码
		// 	// 		console.log(md5.end());
		// 	// 	}
		// 	// };
		// }
		//上传成功
		function handleAvatarSuccess(res) {
			// console.log(res);
			// 七牛云对外域名qiniuData.CName
			const fileUrl = qiniuData.CName + res.key;
			const fileHash = res.hash;
			// console.log(fileUrl);
			scriptForm.key = res.key;
			scriptForm.scriptAddress = fileUrl;
			scriptForm.scriptHash = fileHash;
			setTimeout(() => {
				recordFile(scriptForm);
			}, 1000); // 一秒后执行保存
		}
		//进度条显示
		function onProgress(event, file, fileList) {
			progressFlag.value = true; // 显示进度条
			progress.value = parseInt(event.percent); // 动态获取文件上传进度
			status.value = "exception";
			if (progress.value >= 100) {
				status.value = "success";
				// setTimeout(() => {
				// 	progressFlag.value = false;
				// }, 1000); // 一秒后关闭进度条
			} else if (progress.value >= 50) {
				status.value = "warning";
			}
		}
		//自定义上传操作
		function uploadHttpRequest(option) {
			// 开始上传，token从后端获取， key自定义也可从后端获取（key可以说是文件名）
			const putExtra = {};
			const config = {
				checkByServer: false,
				checkByMD5: false,
				forceDirect: false,
				useCdnDomain: true,
				disableStatisticsReport: false,
				concurrentRequestLimit: 10,
				retryCount: 4,
				chunkSize: 100, //分片时每片大小
				// region: qiniu.region.z2,
				debugLogLevel: "OFF"
			};
			const observable = qiniu.upload(
				option.file,
				qiniuData.key,
				qiniuData.token,
				putExtra,
				config
			);
			let subscription = observable.subscribe({
				// 以下相关代码就是将七牛云的回调函数给el-upload
				//让el-upload能够展示进度条
				next(res) {
					option.onProgress({ percent: res.total.percent });
					if (cance.value == true) {
						console.log("上传取消");
						ElMessage.error("上传取消");
						subscription.unsubscribe(); // 上传取消
					}
				},
				error(err) {
					option.onError(err);
				},
				complete(res) {
					option.onSuccess(res);
				}
			});

			return subscription;
		}
		return {
			form,
			upsert,
			refs,
			table,
			visible,
			setRefs,
			switchPage,
			stopForm,
			onLoad,
			stopTask,
			startTask,
			navTo,
			deviceVisible,
			deviceList,
			scriptVisible,
			navToScript,
			scriptForm,
			recordFile,
			showVersion,
			showUpload,
			beforeAvatarUpload,
			handleAvatarSuccess,
			onProgress,
			progressFlag,
			qiniuData,
			typeOptions,
			selectChanged,
			cancelUp,
			navToFile,
			deleteTask,
			fileVisible,
			fileList,
			deleteFiles,
			cance,
			status,
			progress,
			uploadHttpRequest,
			disabledUpload
		};
	}
});
</script>
<style scoped>
.percentage-value {
	display: block;
	margin-top: 10px;
	font-size: 28px;
}

.percentage-label {
	display: block;
	margin-top: 10px;
	font-size: 12px;
}

.el-progress--line {
	margin-bottom: 15px;
	width: 350px;
}

.el-progress--circle {
	margin-right: 15px;
}
</style>