<template>
	<div>
		<el-breadcrumb separator="/">
		  <el-breadcrumb-item :to="{ path: '/' }">{{$t('mendian.home')}}</el-breadcrumb-item>
		  <el-breadcrumb-item>{{$t('mendian.Management')}}</el-breadcrumb-item>
		  <el-breadcrumb-item>{{$t('mendian.StoreList')}}</el-breadcrumb-item>
		</el-breadcrumb>
		<el-row :gutter="10" style="margin-top: 20px;margin-bottom: 20px;">
		  <el-col :span="1.5">
		    <el-button
		      type="primary"
		      plain
		      icon="el-icon-plus"
		      size="mini"
		      @click="handleAdd"
		    >{{$t('mendian.AddStore')}}</el-button>
		  </el-col>
		</el-row>
		<el-table ref="filterTable" v-loading="loding"  :data="tableData" :header-cell-style="{background:'#f0f0f0'}">
			<el-table-column
				prop="id"
				label="id"
			>
			</el-table-column>
			<el-table-column
				prop="image"
				:label="$t('mendian.StoreCover')"
			>
				<template slot-scope="scope">
					<img style="width: 50px;height: 50px;" :src="seruer+scope.row.image" alt="" />
				</template>
			</el-table-column>
			<el-table-column
				prop="posName"
				:label="$t('mendian.StoreName')"
				width="200"
			>
			</el-table-column>
			<el-table-column
				prop="posPrice"
				:label="$t('mendian.Startingprice')"
				width="200"
			>
			</el-table-column>
<!--			<el-table-column-->
<!--				prop="businessHours"-->
<!--				:label="$t('mendian.businesshours')"-->
<!--			>-->
<!--			</el-table-column>-->
			<el-table-column
				prop="area"
				:label="$t('mendian.area')"
			>
			</el-table-column>
			<el-table-column
				prop="telephone"
				:label="$t('mendian.Telephone')"
				width="200"
			>
			</el-table-column>
			<el-table-column
				fixed="right"
				:label="$t('mendian.operate')"
				width="120">
				<template slot-scope="scope">
					<el-button @click="handleClick(scope.row)" type="text" size="small">{{$t('mendian.modify')}}</el-button>
					<el-button @click="delechansu(scope.row)" type="text" size="small">{{$t('mendian.delete')}}</el-button>
				</template>
			</el-table-column>
		</el-table>
		<div style="width: 100%;display: flex;justify-content: flex-end;">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="queryParams.page"
				:page-size="queryParams.size"
				layout="total, prev, pager, next"
				:total="total">
			</el-pagination>
		</div>
		<!-- 添加或修改门店分类对话框 -->
		<el-dialog :title="text" :visible.sync="open" :width="$t('loding.language')=='en'||$t('loding.language')=='vi'?'650px':'600px'" append-to-body>
		  <el-form ref="form" :model="form" :rules="rules" :label-width="$t('loding.language')=='en'||$t('loding.language')=='vi'?'180px':'100px'">
			<el-form-item :label="$t('mendian.logo')" prop="logo">
			    <el-upload
			      class="avatar-uploader"
			      :action="seruer+'/utils/Upload'"
			      :show-file-list="false"
			      :on-success="handleAvatarlogo"
			      :before-upload="beforeAvatarUpload">
			      <img v-if="form.logo" :src="seruer+form.logo" class="avatar">
			      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
			    </el-upload>
			</el-form-item>
			<el-form-item :label="$t('mendian.StoreCover')" prop="image">
			    <el-upload
			      class="avatar-uploader"
			      :action="seruer+'/utils/Upload'"
			      :show-file-list="false"
			      :on-success="handleAvatarSuccess"
			      :before-upload="beforeAvatarUpload">
			      <img v-if="form.image" :src="seruer+form.image" class="avatar">
			      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
			    </el-upload>
			</el-form-item>
		    <el-form-item :label="$t('mendian.StoreName')" prop="posName">
				<el-input v-model="form.posName" :placeholder="$t('mendian.Enterstorename')" />
		    </el-form-item>
		    <el-form-item :label="$t('mendian.address')" prop="address">
		    	<div style="display: flex;align-items: center;">
					<el-input v-model="form.address" :placeholder="$t('mendian.InputAddress')" />
					<i style="color: #55aaff; margin-left: 10px;font-size: 25px;" class="el-icon-location"  @click="xuanzhemap"></i>
				</div>
		    </el-form-item>
			<el-form-item :label="$t('mendian.coordinate')"  prop="longitude">
				<div style="display: flex;align-items: center;" @click="xuanzhemap">
					<div>{{form.longitude==null?$t('mendian.Positioningobtaincoordinates'):form.longitude+','+form.latitude}}</div>
				</div>
			</el-form-item>
			<el-form-item :label="$t('mendian.Storetype')" prop="type">
				<el-radio v-model="form.type" :label="0" @change="handleTypeChange">{{$t('mendian.Restaurant')}}</el-radio>
				<el-radio v-model="form.type" :label="1" @change="handleTypeChange">{{$t('mendian.Supermarket')}}</el-radio>
			</el-form-item>
			<el-form-item :label="'是否关联夜市'" prop="isNightMarket">
				<el-radio v-model="form.isNightMarket" :label="1">是</el-radio>
				<el-radio v-model="form.isNightMarket" :label="0">否</el-radio>
			</el-form-item>
			<el-form-item v-if="form.isNightMarket === 1" :label="'夜市'" prop="nightMarketId">
				<el-select v-model="form.nightMarketId" placeholder="请选择夜市">
					<el-option
						v-for="item in nightMarketList"
						:key="item.userId"
						:label="item.nickName"
						:value="item.userId">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item :label="$t('mendian.Startingprice')" prop="posPrice">
				<el-input v-model="form.posPrice" :placeholder="$t('mendian.Fillintheprice')" />
			</el-form-item>
			<el-form-item :label="$t('mendian.Telephone')" prop="telephone">
				<el-input v-model="form.telephone" :placeholder="$t('mendian.Fillphonenumber')" />
			</el-form-item>
			<el-form-item :label="$t('mendian.openingtime')" prop="businessHours">
				<div v-for="(item, idx) in form.businessHours" :key="idx" style="display: flex; align-items: center; margin-bottom: 8px;">
				  <el-time-picker
					v-model="item.startTime"
					:placeholder="$t('mendian.FillopenBusiness')"
					value-format="HH:mm"
					format="HH:mm"
					style="width: 110px;"
				  />
				  <span style="margin: 0 8px;">—</span>
				  <el-time-picker
					v-model="item.endTime"
					:placeholder="$t('mendian.FillwindingUp')"
					value-format="HH:mm"
					format="HH:mm"
					style="width: 110px;"
				  />
				  <el-button
					v-if="form.businessHours.length > 1"
					icon="el-icon-minus"
					type="danger"
					size="mini"
					@click="removeBusinessHour(idx)"
					style="margin-left: 8px;"
				  ></el-button>
				</div>
				<el-button
				  icon="el-icon-plus"
				  type="primary"
				  size="mini"
				  @click="addBusinessHour"
				>{{$t('mendian.addTime')}}</el-button>
			</el-form-item>
			<el-form-item :label="$t('mendian.classification')" prop="sort">
				<el-select v-model="form.sort" multiple placeholder="请选择分类" @change="handleSortChange">
				    <el-option
				      v-for="item in fenlei"
				      :key="item.id"
				      :label="$t('loding.language')=='zh-CN'?item.name:$t('loding.language')=='en'?item.nameEn:$t('loding.language')=='zh-TW'?item.nameTw:item.nameVi"
				      :value="item.id">
				    </el-option>
				</el-select>
				<!-- 显示选中的分类名称 -->
				<div v-if="selectedCategoryNames && selectedCategoryNames.length > 0" style="margin-top: 5px;">
					<el-tag
						v-for="(name, index) in selectedCategoryNames"
						:key="index"
						size="small"
						style="margin-right: 5px; margin-bottom: 5px;">
						{{ name }}
					</el-tag>
				</div>
			</el-form-item>
			<el-form-item :label="$t('mendian.ServiceType')" prop="serverType">
				<el-checkbox-group v-model="checkList">
					<el-checkbox v-for="item in fwlxlist" :label="item.id" @change="huoqujieguo">{{$t('loding.language')=='zh-CN'?item.nameCn:$t('loding.language')=='en'?item.nameEn:$t('loding.language')=='zh-TW'?item.nameTw:item.nameVi}}</el-checkbox>
				</el-checkbox-group>
			</el-form-item>
			<el-form-item :label="$t('mendian.state')" prop="state">
				<el-radio v-model="form.state" :label="0">{{$t('mendian.trade')}}</el-radio>
				<el-radio v-model="form.state" :label="1">{{$t('mendian.close')}}</el-radio>
			</el-form-item>
		  </el-form>
		  <div slot="footer" class="dialog-footer">
		    <el-button type="primary" @click="tijiaobaocun">{{$t('mendian.determine')}}</el-button>
		    <el-button @click="cancel">{{$t('mendian.cancellation')}}</el-button>
		  </div>
		</el-dialog>
		<!-- 地图 -->
		<el-dialog :title="$t('mendian.selectaddress')" :visible.sync="opmap" width="1000px" append-to-body>
			<googmap  mapID="googleMap" @golat="huichuandizhi"></googmap>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="dituqiueing">{{$t('mendian.determine')}}</el-button>
				<el-button @click="guanbimay">{{$t('mendian.cancellation')}}</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import {
  getfenlei,
  storelistlist,
  getAddr,
  addmendian,
  delemendian,
  getfwleixing,
  getNightMarketlist,
  getfenleilistByTag
} from '@/api/store';
	import googmap from "@/components/googmap.vue";
	export default{
		name:"AcidrollingCapacity",
		components:{
			 googmap
		},
		data(){
			return {
				seruer: process.env.VUE_APP_BASE_API,
				loding:false,
				tableData:[],
				total:0,
				checkList:[],
				//分页
				queryParams: {
				  page: 1,
				  size: 10,
				},
				fenlei:[],
				fwlxlist:[],
				nightMarketList:[],
				open:false,
				opmap:false,
				form:{
					businessHours: [{ startTime: '', endTime: '' }]
				},
				user:{},
				mdid:'',
				// 表单校验
				rules: {
				  image: [
				    { required: true, message:this.$t('mendian.Covercannotempty'), trigger: "blur" }
				  ],
				  posName: [
				    { required: true, message: this.$t('mendian.Namecannotempty'), trigger: "blur" }
				  ],
				  address: [
				    { required: true, message: this.$t('mendian.Addresscannotempty'), trigger: "blur" }
				  ],
				  longitude: [
				    { required: true, message: this.$t('mendian.Coordinatescannotempty'), trigger: "blur" }
				  ],
				  sort: [
				    {
						type: 'array',
						required: true,
						message: this.$t('mendian.Classifiedmandatory'),
						trigger: "change"
					}
				  ],
				  serverType: [
					{ required: true, message: this.$t('mendian.Selectservicetype'), trigger: "blur" }
				  ],
				  nightMarketId: [
					{
					  validator: (rule, value, callback) => {
						if (this.form.isNightMarket === 1 && (!value || value === null)) {
						  callback(new Error('请选择夜市'));
						} else {
						  callback();
						}
					},
					trigger: 'change'
				  }],
				  businessHours: [
					{
					  validator: (rule, value, callback) => {
						if (!value || value.length === 0) {
						  callback(new Error(this.$t('mendian.zssjd')));
						} else if (value.some(v => !v.startTime || !v.endTime)) {
						  callback(new Error(this.$t('mendian.mgsjd')));
						} else {
						  callback();
						}
				  },
				  trigger: 'change'
				}]
				},
				mapaddress:null,
				text: '',
			}
		},
		computed: {
			// 获取选中分类的名称列表
			selectedCategoryNames() {
				if (!this.form.sort || !Array.isArray(this.form.sort)) {
					return [];
				}
				return this.form.sort.map(id => {
					const category = this.fenlei.find(item => item.id === id);
					if (category) {
						return this.$t('loding.language')=='zh-CN'?category.name:this.$t('loding.language')=='en'?category.nameEn:this.$t('loding.language')=='zh-TW'?category.nameTw:category.nameVi;
					}
					return '';
				}).filter(name => name);
			}
		},
		created() {
			this.getpinguilist();
			this.getfuleix();
			this.getNightMarketList();
			this.user = JSON.parse(localStorage.getItem('user'));
			// console.log('1111111111',this.user);
		},
		methods:{
			huoqujieguo(){
				this.form.serverType = this.checkList.length>0?JSON.stringify(this.checkList):null;
				console.log(this.form.serverType)
			},
			delechansu(e){
				this.$confirm(this.$t('mendian.youwanttodeleteit'), this.$t('mendian.prompt'), {
					confirmButtonText: this.$t('mendian.determine'),
					cancelButtonText: this.$t('mendian.cancellation'),
					type: 'warning'
				}).then(() => {
					delemendian(e.id).then(res=>{
						// console.log('删除',res);
						if(res.code==200){
							this.getpinguilist();
							this.$message({
								type: 'success',
								message: this.$t('mendian.successful')
							});
						}else{
							this.$message({
								type: 'info',
								message: this.$t('mendian.Deletefailed')
							});
						}

					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: this.$t('mendian.undelete')
					});
				});

			},
			tijiaobaocun(){
				this.$refs["form"].validate(valid => {
				  if (valid) {
					// 深拷贝 businessHours，去除响应式属性
					const submitForm = { ...this.form };
					submitForm.businessHours = JSON.parse(JSON.stringify(this.form.businessHours));
					// 确保分类字段是英文逗号分隔的字符串格式
					if (Array.isArray(submitForm.sort)) {
						submitForm.sort = submitForm.sort.join(',');
					}
					console.log('发送到后端的数据:', submitForm);
					console.log('分类字段格式:', submitForm.sort);
					addmendian(submitForm).then(res=>{
						// console.log('操作成功',res)
						if(res.code==200){
							this.getpinguilist();
							this.open = false;
							this.checkList = [];
							this.reset();
						}
					})
				  }
				});

			},
			//地图回传地址
			huichuandizhi(res){
				console.log('地址回传',res);
				console.log('回传数据类型:', typeof res);
				console.log('回传数据内容:', JSON.stringify(res));
				this.mapaddress = res;
				console.log('设置后的mapaddress:', this.mapaddress);
			},
			// 修改门店
			handleClick(res){
				this.text = this.$t('mendian.ModifyStore');
        console.log('修改门店',res);
				this.form = res;
				this.getfenleilistByTag();
				// 确保夜市字段有默认值
				if (this.form.isNightMarket === undefined || this.form.isNightMarket === null) {
					this.form.isNightMarket = 0;
				}
				if (this.form.nightMarketId === undefined || this.form.nightMarketId === null) {
					this.form.nightMarketId = null;
				}
				// 处理分类字段，如果是字符串则转换为数组
				if (typeof this.form.sort === 'string') {
					try {
						// 尝试解析JSON格式
						this.form.sort = JSON.parse(this.form.sort);
					} catch(e) {
						// 如果不是JSON格式，尝试按逗号分割
						if (this.form.sort.includes(',')) {
							this.form.sort = this.form.sort.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id));
						} else {
							this.form.sort = this.form.sort ? [parseInt(this.form.sort)] : [];
						}
					}
				} else if (!Array.isArray(this.form.sort)) {
					this.form.sort = this.form.sort ? [this.form.sort] : [];
				}
				this.checkList = JSON.parse(res.serverType);
				if (res.businessHours && typeof res.businessHours === 'string') {
				  try {
					this.form.businessHours = JSON.parse(res.businessHours);
				  } catch(e) {
					this.$set(this.form, 'businessHours', [{ startTime: '', endTime: '' }]);
				  }
				} else {
				  this.$set(this.form, 'businessHours', res.businessHours || [{ startTime: '', endTime: '' }]);
				}
				if(!Array.isArray(this.form.businessHours) || this.form.businessHours.length === 0) {
				    this.$set(this.form, 'businessHours', [{ startTime: '', endTime: '' }]);
				}
				this.open = true;

			},
			xuanzhemap(){
				this.opmap = true;
				// 重置地图地址数据
				this.mapaddress = null;
			},
			// 确认地址坐标选择
			dituqiueing(){
				console.log('当前地图地址数据:', this.mapaddress);
				if(this.mapaddress==null || !this.mapaddress.address || this.mapaddress.address === '地址获取失败'){
					this.$message.error(this.$t('mendian.Selectmapobtainaddress'));
					return
				}
				this.form.address = this.mapaddress.address;
				var lat = this.mapaddress.lat.split(",");
				this.form.latitude = lat[0];
				this.form.longitude = lat[1];
				console.log('设置坐标:', this.form.latitude, this.form.longitude);
				this.opmap = false;
			},
			guanbimay(){
				this.mapaddress =null;
				this.opmap = false;
			},
			reset() {
				this.form = {
					image: null,
					posName: null,
					posPrice:null,
					area:'',
					address:null,
					longitude:null,
					latitude:null,
					briefIntroduction:null,
					type:0, // 设置默认门店类型为餐厅
					isNightMarket:0,
					nightMarketId:null,
					hygienePermit:null,
					openBusiness:null,
					windingUp:null,
					sort:[],
					userId:this.user.userId,
					state:0,
					serverType:null,
					telephone:null,
					logo:null,
					businessHours: [{ startTime: '', endTime: '' }]
				};
			},
			handleAdd(){
				this.reset();
				this.text = this.$t('mendian.AddStore');
				this.checkList = [];
				// 设置默认门店类型为餐厅(0)
				this.form.type = 0;
				this.open = true;
				// 根据默认门店类型获取对应的分类
				this.getfenleilistByTag();
			},
			cancel() {
			  this.open = false;
			  this.checkList = [];
			  this.reset();
			},
			getpinguilist(){
				var that = this;
				that.loding = true;
				storelistlist(this.queryParams).then(response => {
					that.loding = false;
					this.total = response.data.total;
					this.tableData = response.data.records;
					// console.log("获取门店列表",response);
				});
			},
			getfenlei(){
				getfenlei().then(res=>{
					console.log('获取分类',res);
					this.fenlei = res.rows;
				})
			},
             getfenleilistByTag(){
         if(this.form.type === undefined || this.form.type === null){
           this.$message.warning("请先选择门店类型");
           return;
         }
         let tag = this.form.type === 0 ? "food" : "mall";
         console.log('正在获取分类，门店类型:', this.form.type, '标签:', tag);
         getfenleilistByTag(tag).then(res=>{
           console.log('获取分类成功:', res);
           if (res && res.data) {
             this.fenlei = res.data;
             console.log('分类列表已更新:', this.fenlei);
           } else {
             this.fenlei = [];
             console.log('分类数据为空或格式不正确');
           }
         }).catch(error => {
           console.error('获取分类失败:', error);
           this.$message.error('获取分类失败，请重试');
           this.fenlei = [];
         })
       },
      handleTypeChange(){
        // 清空已选择的分类
        this.form.sort = [];
        // 根据门店类型获取对应的分类
        this.getfenleilistByTag();
      },
      handleSortChange(){
        console.log('分类选择变化:', this.form.sort);
      },
                     // 调试方法：检查分类数据状态
        debugCategoryData(){
          console.log('=== 分类数据调试信息 ===');
          console.log('门店类型:', this.form.type);
          console.log('分类列表长度:', this.fenlei ? this.fenlei.length : 0);
          console.log('分类列表数据:', this.fenlei);
          console.log('已选择的分类:', this.form.sort);
          console.log('选中的分类名称:', this.selectedCategoryNames);
          console.log('分类数据类型:', typeof this.form.sort);
          console.log('分类数据是否为数组:', Array.isArray(this.form.sort));
          if (typeof this.form.sort === 'string') {
            console.log('字符串格式的分类数据:', this.form.sort);
          }
          console.log('======================');
        },
			getfuleix(){
				getfwleixing().then(res=>{
					console.log('获取服务类型',res);
					this.fwlxlist = res.rows;
				})
			},
			getNightMarketList(){
				getNightMarketlist().then(res=>{
					console.log('获取夜市列表',res);
					this.nightMarketList = res.data || [];
				})
			},
			//翻页
			handleSizeChange(val) {
				// console.log(`每页 ${val} 条`);
				this.queryParams.size = val;
				this.getpinguilist();
			},
			handleCurrentChange(val) {
				// console.log(`当前页: ${val}`);
				this.queryParams.page = val;
				this.getpinguilist();
			},
			handleAvatarlogo(res, file) {
				// this.upimg = URL.createObjectURL(file.raw);
				this.form.logo = file.response.data;
				// console.log('上传图片',file.response);

			},
			handleAvatarSuccess(res, file) {
				// this.upimg = URL.createObjectURL(file.raw);
				this.form.image = file.response.data;
				// console.log('上传图片',file.response);

			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 2;

				if (!isJPG) {
				  this.$message.error(this.$t('mendian.ItcanonlyJPG'));
				}
				if (!isLt2M) {
				  this.$message.error(this.$t('mendian.Cannotexceed'));
				}
				return isJPG && isLt2M;
			},
			addBusinessHour() {
			  this.form.businessHours.push({ startTime: '', endTime: '' });
			},
			removeBusinessHour(idx) {
			  this.form.businessHours.splice(idx, 1);
			},
		}
	}
</script>

<style>
	.avatar-uploader .el-upload {
	    border: 1px dashed #d9d9d9;
	    border-radius: 6px;
	    cursor: pointer;
	    position: relative;
	    overflow: hidden;
	  }
	  .avatar-uploader .el-upload:hover {
	    border-color: #409EFF;
	  }
	  .avatar-uploader-icon {
	    font-size: 28px;
	    color: #8c939d;
	    width: 100px;
	    height: 100px;
	    line-height: 100px;
	    text-align: center;
	  }
	  .avatar {
	    width: 100px;
	    height: 100px;
	    display: block;
	  }
</style>
