<script setup lang="ts">
import AppBlock from '@/components/AppBlock.vue'
import HomeHead from '@/views/home/components/HomeHead.vue'
// import HomeHeadSearch from '@/views/home/components/HomeHeadSearch.vue'
import { useMessage, NModal } from 'naive-ui'
import { useUserStore } from '@/stores/modules/user'
import UserList from '@/views/home/intelligence/process/UserPages.vue'
import dayjs from 'dayjs'

import {
	fetchDelHis,
	marketPreADD,
	getMetalList,
	fetchGetHisPage,
	fetchUpdateHis,
	fetchSaveHis
} from '@/api/daikin/base'

const message = useMessage()
const store = useUserStore()
const header = { token: store.user.token }

const dataA = ref<any>([])
const editA = ref<any>({ stDateList: [] })
const metaList = ref<any>([])
const metaObj = ref<any>({})

const stDateList = ref<any>([])
const shomkA = ref(false)

const type = ref(2)
async function getDataA() {
	const { data } = await fetchGetHisPage({})
	dataA.value = Object.entries(data).map(([key, value]: any) => {
		return {
			stDate: key,
			yearId: key,
			children: value.map((item: any) => {
				return {
					...item,
					numbers: metaObj.value[item.number]
				}
			})
		}
	})
	// setDataFiles(dataArr);
}

onMounted(async () => {
	const { data = [] } = await getMetalList()
	metaList.value = data
	data.forEach((item: any) => {
		metaObj.value[item.value] = item.title
	})
	getDataA()
})

async function onSubmitA(row: { id: any; fileList?: any; title?: any }) {
	console.log(row, 555)
	const { id, title } = row
	// let moduleId = 1;
	let sendData = {}
	if (!row.id) {
		sendData = { title, type: type.value, userIdList: userData.value }
		if (row.fileList && row.fileList.length > 0) {
			row.fileList.map((item) => {
				if (item.response) {
					sendData.filePath = item.response.url
					// obj.title = title || computedName(item.response.originalFilename);
				} else {
					sendData.filePath = item.url
					// obj.title = title || computedName(item.originalFilename);
				}
			})
		}
	} else {
		sendData = { id, title, type: type.value, userIdList: userData.value }
	}
	const { code, msg } = await marketPreADD(sendData)
	if (code === 200) {
		message.success('修改成功！')
	} else {
		message.error(msg)
	}
	shomkA.value = false
	getDataA()
}

const handleEditA = (type: string, row: any = {}) => {
	if (!row) return
	editA.value = { ...row }
	editA.value.stDateList = [row.stDate, row.stDate]
	stDateList.value = [row.stDate, row.stDate]
	// setUserList.value =[]
	shomkA.value = true

	// editA.value.fileList = [{
	//   name: row.title,
	//   originalFilename: row.title,
	//   url: row.filePath,
	// }]
	// setUserList.value =row.userIdList
}

async function handleDeleteA(index: number, row: any) {
	const { id } = row
	if (!id) return
	const { code, msg } = await fetchDelHis({ id, type: type.value })
	if (code === 200) {
		message.success('删除成功！')
	} else {
		message.error(msg)
	}
	getDataA()
}

const showModal = ref(false)
const flg = ref()
const setUserList = ref()
async function getUser(row) {
	console.log(row)
	showModal.value = !showModal.value
	flg.value = row
	if (row.id && row.userIdList) {
		setUserList.value = row.userIdList
	}
	// const {data: userArr} = await getBPCUser({moduleId})
	// setUserList.value = userArr
}
// 获取子组件传过来的值
const userData = ref()
const handleChild = (data: any) => {
	const { showModal: show, multipleSelection } = data
	showModal.value = unref(show)
	let userIdList: any[] = []
	multipleSelection.value.forEach((i: { userId: any }) => {
		userIdList.push(i.userId)
	})
	if (flg.value.id) {
		flg.value.userIdList = userIdList
		marketPreADD(flg.value)
		getDataA()
		console.log(flg.value)
	}
	userData.value = userIdList
}
const CloseThiss = (data: boolean) => {
	showModal.value = data
}
const goBacks = () => {
	history.back()
}

const editForm = ref(null)
const channelList = ref([
	{
		label: 'LME',
		value: 'LME'
	},
	{
		label: 'SMM',
		value: 'SMM'
	}
])

const handleClickA = async () => {
	if (stDateList.length == 0) {
		message.error('请选择日期!')
		return
	}
	const req = { ...editA.value }
	req.stDateList = generateDateRange()
	console.log('🚀 ~ file: dataModify.vue:173 ~ req:', req)
	let res: any = await fetchSaveHis(req)
	if (res.code == 200) {
		shomkA.value = false
		message.success('操作成功！')
		getDataA()
	} else {
		message.error(res.msg)
	}
}

function generateDateRange() {
	const [startDate, endDate] = stDateList.value || []
	if (!startDate || !endDate) return []
	const dateFormat = 'YYYY-MM-DD'
	const dates = []

	const start = dayjs(startDate, dateFormat)
	const end = dayjs(endDate, dateFormat)

	// 将开始日期添加到数组中
	dates.push(start.format(dateFormat))

	// 逐步增加日期，直到结束日期
	let currentDate = start
	while (currentDate.isSameOrBefore(end)) {
		currentDate = currentDate.add(1, 'day')
		dates.push(currentDate.format(dateFormat))
	}

	return dates
}
</script>
<template>
	<HomeHead class="top">
		<template #content>
			<!-- <HomeHeadSearch /> -->
		</template>
	</HomeHead>
	<AppBlock class="w-full h950px p30px text-#000">
		<div class="font-600 flex items-center">
			<!-- <img src="./images/logo.svg" class="h56px mr21px" /> -->
			<div class="text-36px text-#000">市况数据管理</div>
		</div>
		<div class="cont relative w100% h800px overflow-y-auto">
			<el-button type="primary" @click="handleEditA" class="my20px"
				>市况数据新增</el-button
			>
			<div
				class="rounded-md float-right mr-80px mt-20px px20px py10px z-200 bg-#f5f5f5 flex items-center justify-center w-100px"
				@click="goBacks"
			>
				<el-icon><ArrowLeftBold size="18" /></el-icon> 返回
			</div>
			<el-table
				:data="dataA"
				style="width: 95%"
				row-key="yearId"
				:header-cell-style="{
					background: '#2A7BF7',
					color: '#fff',
					height: '60px',
					textAlign: 'center',
					'font-size': '24px'
				}"
				:cell-style="{ 'text-align': 'center' }"
				height="700px"
			>
				<el-table-column label="日期" prop="stDate" />
				<el-table-column label="渠道" prop="channel" />
				<el-table-column label="编号" prop="numbers" />
				<el-table-column label="金额" prop="negAmount" />

				<!-- <el-table-column label="查看范围" prop="userIdList"> 
                  <template  #default="scope">
                    <span v-if="scope.row.userIdList" v-for="it in scope.row.userIdList"> &nbsp;&nbsp; {{it.nickName}}</span>
                  </template>
                </el-table-column> -->
				<el-table-column label="操作" width="180px">
					<template #default="scope">
						<template v-if="!scope.row.children?.length">
							<el-button size="small" @click="handleEditA('edit', scope.row)"
								>编辑</el-button
							>
							<el-button
								size="small"
								type="danger"
								@click="handleDeleteA(scope.$index, scope.row)"
								>删除</el-button
							>
						</template>
					</template>
				</el-table-column>
			</el-table>
		</div>
	</AppBlock>

	<el-dialog
		:z-index="200"
		v-model="shomkA"
		title="  "
		width="30%"
		:modal="false"
		top="30vh"
		@close="editForm?.resetFields()"
	>
		<div class="bg-#FFF">
			<el-form ref="editForm" :model="editA" label-width="100px" size="large">
				<el-form-item label="日期" prop="stDate">
					<!-- <el-date-picker
					class="!w-90%"
						v-model="editA.stDate"
						type="date"
						placeholder="选择日期"
						value-format="YYYY-MM-DD"
					/> -->
					<el-date-picker
						v-model="stDateList"
						type="daterange"
						range-separator="至"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
						value-format="YYYY-MM-DD"
						class="!w-90%"
					/>
				</el-form-item>
				<br />
				<el-form-item label="渠道" prop="channel">
					<el-select
						:disabled="editA.id"
						v-model="editA.channel"
						placeholder="选择渠道"
						class="!w-100%"
					>
						<el-option
							v-for="item in channelList"
							:key="item.value"
							:label="item.label"
							:value="item.value"
						/>
					</el-select>
				</el-form-item>
				<br />
				<el-form-item label="编号" prop="number">
					<el-select
						:disabled="editA.id"
						v-model="editA.number"
						placeholder="选择类型"
						class="!w-100%"
					>
						<el-option
							v-for="item in metaList"
							:key="item.value"
							:label="item.title"
							:value="item.value"
						/>
					</el-select>
				</el-form-item>
				<br />
				<el-form-item label="数值" prop="negAmount">
					<el-input-number
						v-model="editA.negAmount"
						:controls="false"
						class="!w-100%"
					/>
				</el-form-item>
				<br />
				<div class="text-center">
					<el-button
						type="primary"
						@click="handleClickA(editA)"
						class="mb-20px"
					>
						确认</el-button
					>
				</div>
			</el-form>
		</div>
	</el-dialog>

	<n-modal v-model:show="showModal">
		<UserList
			:userDataList="setUserList"
			@clickChild="handleChild"
			@CloseThis="CloseThiss"
		/>
	</n-modal>
</template>

<style lang="less" scoped>
.demo-tabs > .el-tabs__content {
	color: #6b778c;
	font-size: 32px;
	font-weight: 600;
}
.top {
	position: absolute;
	right: 30px;
	top: -92px;
}
.flex-center {
	display: flex;
	justify-content: center;
	margin: 0 auto;
}
:deep(.el-input-number .el-input__inner) {
	text-align: left !important;
}
:deep {
	.el-dialog__body {
		margin-top: 18px;
		padding-top: 10px;
	}
}
</style>
