<template>
	<!-- 营销-积分商品 -->
	<div>
		<Card :bordered="false" dis-hover class="ivu-mt" :padding="0">
			<div class="new_card_pd">
				<!-- 查询条件 -->

				<Form ref="tableFrom" inline :model="tableFrom" :label-width="labelWidth"
					:label-position="labelPosition" @submit.native.prevent>
					<!-- <FormItem label="创建时间：" label-for="user_time">
            <DatePicker
                :editable="false"
                @on-change="onchangeTime"
                :value="timeVal"
                format="yyyy/MM/dd"
                type="datetimerange"
                placement="bottom-start"
                placeholder="自定义时间"
                class="mr20 input-add"
                :options="options"
            ></DatePicker>
          </FormItem> -->
					<!-- <FormItem label="上架状态：">
            <Select
                placeholder="请选择"
                clearable
                class="input-add"
                v-model="tableFrom.is_show"
            >
              <Option value="1">上架</Option>
              <Option value="0">下架</Option>
            </Select>
          </FormItem> -->
					<FormItem label="门店：">
						<Select v-model="tableFrom.store_id" clearable filterable @on-change="userSearchs"
							class="input-add">
							<Option v-for="item in staffData" :value="item.id" :key="item.id" :label="item.name">
								{{item.id}}-{{ item.name }}
							</Option>
						</Select>
					</FormItem>
					<!-- <Button type="primary" @click="add" class="mr10">添加镜像</Button>
					<Button v-auth="['export-storeSeckill']" class="export" icon="ios-share-outline"
						@click="exports">导出</Button> -->
				</Form>
			</div>
		</Card>
		<Card :bordered="false" dis-hover class="ivu-mt">
			<!-- 操作 -->
			<Button v-auth="['admin-erp-product_add']" type="primary" @click="add" class="mr10">添加镜像</Button>
			<!-- 积分商品-表格 -->
			<Table :columns="columns1" :data="tableList" :loading="loading" highlight-row no-userFrom-text="暂无数据"
				no-filtered-userFrom-text="暂无筛选结果" class="ivu-mt">
				<template slot-scope="{ row, index }" slot="passageway">
					<span> {{ row.bin_number.slice(0,2) }}</span>
				</template>
				<template slot-scope="{ row, index }" slot="control">
					<span> {{ row.bin_number.slice(2,3) }}</span>
				</template>
				<template slot-scope="{ row, index }" slot="layer">
					<span> {{ row.bin_number.slice(3,4) }}</span>
				</template>
				<template slot-scope="{ row, index }" slot="number">
					<span> {{ row.bin_number.slice(4) }}</span>
				</template>
				<template slot-scope="{ row, index }" slot="is_show">
					<i-switch v-auth="['admin-erp-product-setshow']" v-model="row.is_show" :value="row.is_show"
						:true-value="1" :false-value="0" @on-change="changeSwitch(row)" size="large">
						<span slot="open">上架</span>
						<span slot="close">下架</span>
					</i-switch>
				</template>
				<template slot-scope="{ row, index }" slot="unit_name_1">
					<div v-if="row.unit_name_1">
						<div>名称：{{row.unit_name_1}}</div>
						<div>转换率：1{{row.unit_name_1}} = {{row.unit_rate_1*1}}{{row.unit_name}}</div>
					</div>
				</template>
				<template slot-scope="{ row, index }" slot="unit_name_2">
					<div v-if="row.unit_name_2">
						<div>名称：{{row.unit_name_2}}</div>
						<div>转换率：1{{row.unit_name_2}} = {{row.unit_rate_2*1}}{{row.unit_name}}</div>
					</div>
				</template>
				<template slot-scope="{ row, index }" slot="is_weigh">
					{{row.is_weigh == 1?'是': '否'}}
				</template>
				<template slot-scope="{ row, index }" slot="action">
					<!-- 	<a @click="look(row)">详情</a>
					<Divider type="vertical" /> -->
					<a @click="edit(row)" v-auth="['admin-erp-product_add']">编辑</a>
					<!-- <template v-auth="['admin-erp-product-del']">
						<Divider type="vertical" />
						<a @click="del(row, '删除商品', index)">删除</a>
					</template> -->
					<template v-auth="['admin-erp-product-del']">
						<Divider type="vertical" />
						<a @click="tbprod(row,index)">同步商品</a>
					</template>
				</template>
			</Table>
			<div class="acea-row row-right page">
				<Page :total="total" :current="tableFrom.page" show-elevator show-total @on-change="pageChange"
					:page-size="tableFrom.limit" />
			</div>
		</Card>
		<Modal v-model="modal" scrollable title="创建" class="order_box" :closable="false" :mask-closable="false">
			<Form ref="remarks" :model="remarks" :label-width="80" @submit.native.prevent>
				<FormItem label="门店：">
					<Select v-model="remarks.store_id" clearable filterable @on-change="storeChoose" class="input-add">
						<Option v-for="item in staffData" :value="item.id" :key="item.id">{{ item.name }}
						</Option>
					</Select>
				</FormItem>
				<FormItem label="创建人：">
					<Select v-model="remarks.create_uid" clearable filterable @on-change="userSearchse" class="input-add">
						<Option v-for="item in authLists" :value="item.id" :key="item.id">{{ item.staff_name }}
						</Option>
					</Select>
				</FormItem>
			</Form>
			<div slot="footer">
				<Button type="primary" @click="putRemark()">创建</Button>
				<Button @click="cancel()">取消</Button>
			</div>
		</Modal>
		<!-- <productDetail ref="productDetail"></productDetail> -->
	</div>
</template>

<script>
	import {
		staffListInfo
	} from "@/api/store";
	import {
		mapState
	} from "vuex";
	import {
		productInfoApi,
		cascaderListApi,
		productAddApi,
		generateAttrApi,
		productGetRuleApi,
		productGetTemplateApi,
		productGetTempKeysApi,
		checkActivityApi,
		labelListApi,
		productCache,
		cacheDelete,
		brandList,
		productCreateApi,
		productAllUnit,
		productUnitCreate,
		uploadType,
		productAllEnsure,
		productLabelAdd,
		productAllSpecs,
		allSystemForm
	} from "@/api/product";
	import {
		integralProductListApi,
		integralIsShowApi,
		storeSeckillApi,
	} from "@/api/marketing";
	import {
		mirrorList,
		getUserInfo,
		getGoodInfo,
		setShow,
		mainSetShow,
		mirrorExport,
		getUserList,
		addMirror
	} from "@/api/erp";
	import {
		formatDate
	} from "@/utils/validate";
	import timeOptions from "@/utils/timeOptions";
	import Setting from "@/setting";
	// import productDetail from './productDetail.vue'
	import exportExcel from "@/utils/newToExcel.js";
	export default {
		name: "jingxiang",
		filters: {
			formatDate(time) {
				if (time !== 0) {
					let date = new Date(time * 1000);
					return formatDate(date, "yyyy-MM-dd");
				}
			},
		},
		data() {
			return {
				remarks: {
					create_uid: '',
					create_admin_id: '',
					store_id: '',
				},
				modal: false,
				staffData: [],
				stId: '',
				jgTime: 50,
				roterPre: Setting.roterPre,
				loading: false,
				options: timeOptions,
				columns1: [{
						title: "ID",
						key: "id",
						width: 80,
					},
					{
						title: "商品名称",
						key: "store_name",
						minWidth: 90,
					},

					{
						title: "总销量",
						key: "all_sales",
						minWidth: 90,
					},
					{
						title: "总库存",
						key: "stock",
						minWidth: 90,
					},
					{
						title: "单位",
						key: "unit_name",
						minWidth: 90,
					},
					{
						title: "上下架",
						slot: "is_show",
						minWidth: 90,
					},
					{
						title: "大单位",
						slot: "unit_name_1",
						minWidth: 90,
					},
					{
						title: "超大单位",
						slot: "unit_name_2",
						minWidth: 90,
					},
					{
						title: "商品条码",
						key: "bar_code",
						minWidth: 90,
					},
					{
						title: "成本价",
						key: "cost",
						minWidth: 90,
					},
					{
						title: "是否称重",
						slot: "is_weigh",
						minWidth: 90,
					},
					{
						title: "操作",
						slot: "action",
						fixed: "right",
						width: 200,
					},
				],
				tableList: [],
				timeVal: [],
				grid: {
					xl: 7,
					lg: 10,
					md: 12,
					sm: 24,
					xs: 24,
				},
				tableFrom: {
					// integral_time: "",
					// is_show: "",
					// store_name: "",
					store_id: '',
					key: '',
					page: 1,
					limit: 10,
				},
				total: 0,
				loadingss: false,
				isDan: false,
				ylprod: [],
				ylLen: 0,
				authLists: []
			};
		},
		computed: {
			...mapState("admin/layout", ["isMobile"]),
			labelWidth() {
				return this.isMobile ? undefined : 96;
			},
			labelPosition() {
				return this.isMobile ? "top" : "right";
			},
		},
		created() {
			this.getList();
			this.staffList()
		},
		methods: {
			putRemark() {
				addMirror(this.remarks).then(res => {
					
				})
			},
			cancel(){
				this.remarks = {
					create_admin_id: '',
					create_uid: '',
					store_id: ''
				};
				this.modal = false
			},
			userSearchse(e) {
				let auth = this.authLists.find(item => item.id == e)
				this.remarks.create_admin_id = auth.admin_id
			},
			handleFileSelect(event) {
				console.log(event, 'event')
				const file = event.target.files[0]
				const reader = new FileReader()
				reader.readAsText(file, "UTF-8")
				reader.onload = (evt) => {
					let fileString = evt.target.result;
					fileString = fileString.replace(/\n/g, ',').replace(/\r/g, '')
					// const count = fileString.trim().split('\n').length
					this.ylprod = fileString.split(',');
					this.ylLen = this.ylprod.length;
					// this.bgProd()
					// console.log(typeof(fileString),fileString,arr,'fileString',evt)
					// this.dataArr = []
					// for (let index = 1; index < count; index++) {
					// 	const fileline = fileString.split("\r\n")[index].split(",")[0]
					// 	const filelineNumber = (fileline.split(/\s+/)).map(Number)
					// 	this.dataArr.push(filelineNumber)
					// }
				}
			},
			bgProd(index = 0) {
				let that = this
				if (index == that.ylLen) return;
				// 获取商品信息
				getGoods({
					id: that.ylprod[index]
				}).then(res => {
					// console.log(res.data.data)
					let arr = res.data.data;
					if (arr.length > 0) {
						let qdata = that.setUpdate(arr[0])
						// console.log(qdata)
						productAddApi(qdata).then(ress => {
							that.$Message.success(ress.msg);
							index++;
							that.bgProd(index);

						})
					}
				})
			},
			tbprod(row, index) {
				this.isDan = true;
				this.upGoods(row, index)
			},
			changeSwitch(row) {
				console.log(row, row.id, row.is_show)
				if (!this.tableFrom.store_id) {
					mainSetShow({
						id: row.id,
						is_show: row.is_show
					}).then(res => {
						this.$Message.success(res.msg);
						this.getList(1)
					}).catch(err => {
						this.$Message.success(err.msg);
						this.getList(1)
					})
				} else {
					setShow({
						store_id: this.tableFrom.store_id,
						id: row.id,
						is_show: row.is_show
					}).then(res => {
						this.$Message.success(res.msg);
						this.getList(1)
					}).catch(err => {
						this.$Message.success(err.msg);
						this.getList(1)
					})
				}
			},
			staffList() {
				staffListInfo()
					.then((res) => {
						this.staffData = res.data;
					})
					.catch((err) => {
						this.$Message.error(err.msg);
					});
			},
			userSearchs(e) {
				this.getList(1)
			},
			begin(index = 0) {
				// if(this.)
				let that = this;
				let len = that.tableList.length;
				if (index == len) {
					this.tableFrom.page++;
					this.loadingss = true
					this.getList()
					return;
				};
				console.log('开始');
				setTimeout(() => {
					that.upGoods(that.tableList[index], index)
				}, that.jgTime)
				// that.upGoods(that.tableList[index],index)
			},
			setUpdate(good) {
				return {
					"stock": 10,
					"is_weigh": good.is_weigh,
					"applicable_store_id": [],
					"system_form_id": 0,
					"is_presale_product": 0,
					"is_limit": 0,
					"limit_type": 1,
					"limit_num": 1,
					"is_vip_product": 0,
					"is_support_refund": 1,
					"disk_info": "",
					"presale_day": 1,
					"presale_time": [],
					"auto_on_time": "",
					"video_open": false,
					"store_name": good.store_name,
					"freight": 1,
					"postage": 0,
					"custom_form": [],
					"cate_id": [
						1,
						2
					],
					"label_id": [],
					"ensure_id": [],
					"keyword": "",
					"applicable_type": 0,
					"unit_name": good.unit_name,
					"specs_id": 0,
					"store_info": "",
					"bar_code": good.bar_code,
					"code": "",
					"image": "",
					"recommend_image": "",
					"slider_image": [
						"https://shop.yiqucguoyuan.com/uploads/attach/2024/07/20240724/efb26cf8e741fa950209589f58e0df5a.png"
					],
					"description": "<p>" + good.store_name + "<br/></p>",
					"ficti": 0,
					"give_integral": 0,
					"sort": 0,
					"is_show": 1,
					"is_hot": 0,
					"is_benefit": 0,
					"is_best": 0,
					"is_new": 0,
					"is_good": 0,
					"is_postage": 0,
					"is_sub": [],
					"id": 0,
					"spec_type": 0,
					"video_link": "",
					"temp_id": "",
					"attrs": [{
						"pic": "https://shop.yiqucguoyuan.com/uploads/attach/2024/07/20240724/efb26cf8e741fa950209589f58e0df5a.png",
						"price": good.price,
						"settle_price": 0,
						"cost": 0,
						"ot_price": 0,
						"erp_product_id": good.id,
						"unit": good.unit_name,
						"uint_to_erp_unit": 1,
						"bar_code": good.bar_code,
						"code": "",
						"weight": good.is_weigh,
						"volume": 0,
						"brokerage": 0,
						"brokerage_two": 0,
						"vip_price": good.vip_price,
						"virtual_list": [],
						"write_times": 0,
						"write_valid": 1,
						"days": 1
					}],
					"items": [],
					"activity": [
						"默认",
						"秒杀",
						"砍价",
						"拼团"
					],
					"couponName": [],
					"header": [],
					"selectRule": "",
					"coupon_ids": [],
					"command_word": "",
					"delivery_type": [
						"1",
						"3",
						"2"
					],
					"specs": [],
					"recommend_list": [],
					"brand_id": [],
					"product_type": 0,
					"type": 0,
					"store_label_id": []
				}
			},
			upGoods(good, index) {
				let qdata = this.setUpdate()
				if (this.stId && this.stId > good.id) {
					return;
				}
				productAddApi(qdata).then(res => {
					this.$Message.success(res.msg);
					if (this.isDan) {
						return this.isDan = false;
					} else {
						index++;
						this.begin(index);
					}

				})
			},
			look(row) {
				try {
					this.$refs.productDetail.getInfo(row.id)
				} catch (e) {
					//TODO handle the exception

				}
				// getGoodInfo(row.id).then(res=> {
				// 	console.log(res,'商品详情');
				// })

			},
			// 添加
			add() {
				this.modal = true
				// this.$router.push({
				// 	path: this.roterPre + "/erp/product_add?id=0"
				// });
			},
			storeChoose(row) {
				console.log('xje',row)
				try{
					let qdata = {}
					qdata.store_id = row;
					this.authLists = [];
					this.remarks.create_uid = '';
					this.remarks.create_admin_id = '';
					getUserList(qdata).then(res => {
						this.authLists = res.data.data;
					})
				}catch(e) {
					console.log(e)
				}
				
		},
		addMore() {
			this.$router.push({
				path: this.roterPre + "/marketing/store_integral/add_store_integral",
			});
		},
		orderList(row) {
			this.$router.push({
				path: this.roterPre + "/marketing/store_integral/order_list",
				query: {
					product_id: row.id,
				},
			});
		},
		// 导出
		exports() {
			mirrorExport({
					store_id: this.tableFrom.store_id
				})
				.then((res) => {
					// location.href = res.data[0];
					let data = res.data
					exportExcel(data.header, data.filekey, data.fileName, data.export);
				})
				.catch((res) => {
					this.$Message.error(res.msg);
				});
		},
		// 编辑
		edit(row) {
			this.$router.push({
				path: this.roterPre + "/erp/product_add?id=" + row.id
			});
		},
		// 一键复制
		copy(row) {
			this.$router.push({
				path: this.roterPre + "/marketing/store_integral/create/" + row.id + "/1",
			});
		},
		// 删除
		del(row, tit, num) {
			let delfromData = {
				title: tit,
				num: num,
				url: `/erp/goods/del/${row.id}`,
				method: "DELETE",
				ids: "",
			};
			this.$modalSure(delfromData)
				.then((res) => {
					this.$Message.success(res.msg);
					this.tableList.splice(num, 1);
					if (!this.tableList.length) {
						this.tableFrom.page =
							this.tableFrom.page == 1 ? 1 : this.tableFrom.page - 1;
					}
					this.getList();
				})
				.catch((res) => {
					this.$Message.error(res.msg);
				});
		},
		// 列表
		getList() {
			this.loading = true;
			// this.tableFrom.start_status = this.tableFrom.start_status || "";
			// this.tableFrom.is_show = this.tableFrom.is_show || "";
			mirrorList(this.tableFrom)
				.then(async (res) => {
					let data = res.data;
					this.tableList = data.data;
					this.total = data.count;
					this.loading = false;
					if (this.loadingss && this.tableList.length > 0) {
						this.begin(0)
					}
				})
				.catch((res) => {
					this.loading = false;
					this.$Message.error(res.msg);
				});
		},
		pageChange(index) {
			this.tableFrom.page = index;
			this.getList();
		},
		// 表格搜索
		tableSearchs() {
			this.tableFrom.page = 1;
			this.getList();
		},
		// 具体日期
		onchangeTime(e) {
			this.timeVal = e;
			this.tableFrom.integral_time = this.timeVal[0] ? this.timeVal.join("-") : "";
		},
		// 修改是否显示
		onchangeIsShow(row) {
			let data = {
				id: row.id,
				is_show: row.is_show,
			};
			integralIsShowApi(data)
				.then(async (res) => {
					this.$Message.success(res.msg);
				})
				.catch((res) => {
					this.$Message.error(res.msg);
				});
		},
	},
	};
</script>

<style scoped lang="stylus">
	.tabBox_img {
		width: 36px;
		height: 36px;
		border-radius: 4px;
		cursor: pointer;

		img {
			width: 100%;
			height: 100%;
		}
	}
</style>