<template>
	<view class="container">
		<view class="top-box">
			为了方便我们与您尽快联系达成合作，请如实填写以下资料，谢谢您的支持与配合
		</view>

		<u-form :model="storeInfo" ref="uForm" labelPosition="left" :rules="rules" labelWidth="80">
			<view class="content-box">
				<view class="content-item">
					<u-form-item prop="legalRepresentativeName" required label="姓名" right>
						<view class="item-r">
							<u--input placeholder="请输入负责人名称" border="surround"
								v-model="storeInfo.legalRepresentativeName"></u--input>
						</view>
					</u-form-item>
				</view>
				<view class="content-item">
					<u-form-item prop="mobileNumber" required label="手机号码" right>
						<view class="item-r">
							<u--input placeholder="请输入手机号码" border="surround"
								v-model="storeInfo.mobileNumber"></u--input>
						</view>
					</u-form-item>
				</view>

				<view class="content-item">
					<u-form-item prop="email" required label="电子邮箱" right>
						<view class="item-r">
							<u--input placeholder="请输入您的邮箱" border="surround" v-model="storeInfo.email"></u--input>
						</view>
					</u-form-item>
				</view>
			</view>
			<view class="content-box">
				<view class="content-item">
					<u-form-item prop="storeName" required label="店铺名称" right>
						<view class="item-r">
							<u--input placeholder="请输入店铺名称" border="surround" v-model="storeInfo.storeName"></u--input>
						</view>
					</u-form-item>
				</view>
				<view class="content-item">
					<u-form-item prop="storeAddress" required label="所在地区" right>
						<view class="item-r">
							<u--input placeholder="请选择所在地区" border="surround" v-model="storeAddress"
								@focus="handlerChange"></u--input>
						</view>
						<view class="icon-right-box">
							<u-icon name="arrow-right" color="#c5c5c5" size="20"></u-icon>
						</view>
					</u-form-item>
				</view>
				<view class="content-item">
					<u-form-item prop="storeAddressDetail" required label="详细地址" right>
						<!-- <view class="item-r">
              <u--input placeholder="请输入门店详细地址" border="surround" v-model="storeInfo.storeAddressDetail"></u--input>
            </view> -->
						<view class="item-r" @click.stop="manualGetLocation">
							<u--input placeholder="请选择详细地址" border="surround"
								v-model="storeInfo.storeAddressDetail"></u--input>
						</view>
						<view class="icon-right-box">
							<u-icon name="arrow-down-fill" color="#333333" size="20"></u-icon>
						</view>
					</u-form-item>
				</view>
			</view>
			<!-- 商家信息 -->
			<view class="content-box">
				<view class="content-item">
					<u-form-item prop="mainBusiness" required label="主营业务" right>
						<view class="item-r">
							<u--input placeholder="请选择主营业务" border="surround" v-model="mainBusinessName"
								@focus="handlerChangeMainBusiness"></u--input>
						</view>
						<view class="icon-right-box">
							<u-icon name="arrow-right" color="#c5c5c5" size="20"></u-icon>
						</view>
					</u-form-item>
				</view>
				<view class="content-item">
					<u-form-item prop="ancillaryBusiness"  label="辅营业务" right>
						<view class="item-r">

							<!-- #ifndef APP-NVUE -->
							<u-input placeholder="请选择辅营业务" v-model="ancillaryBusinessName.join(',')" clearable
								@clear="ancillaryBusinessClear">
							<!-- #endif -->
								<!-- #ifdef APP-NVUE -->
								<u--input placeholder="sadasd">
								<!-- #endif -->
									<template slot="suffix">
										<u-icon @click="handlerChangeAncillaryBusiness" name="arrow-right"
											color="#c5c5c5" size="20"></u-icon>
									</template>
							<!-- #ifndef APP-NVUE -->
							</u-input>
							<!-- #endif -->
						</view>
					</u-form-item>
				</view>



				<view class="content-item">
					<u-form-item prop="opening" required label="营业时间" right>
						<view class="item-r">
							<u--input placeholder="请输入营业时间" border="surround" v-model="storeInfo.opening"></u--input>
						</view>
					</u-form-item>
				</view>
			</view>

			<view class="content-box">
				<u-form-item prop="storeImage">
					<imgs-upload @update="fileList" :value="1" :imageList="storeInfo.storeImage"></imgs-upload>
					<p class="upload-text">店铺门面图(需要包含完整牌匾)</p>
				</u-form-item>
			</view>

			<view class="content-box">
				<u-form-item prop="storeInnerImage">
					<imgs-upload @update="fileList" :value="2"
						:imageList="storeInfo.storeInnerImage.join(',')"></imgs-upload>
					<p class="upload-text">店内真实环境图</p>
				</u-form-item>
			</view>
		</u-form>
		<button class="btn" @click="handlerSkipNext">下一步</button>

		<!-- 选择器 -->
		<u-picker :show="show" ref="uPicker" :columns="list" keyName="name" @confirm="confirm" @change="changeHandler"
			@cancel="show = false"></u-picker>

	</view>
</template>

<script>
import ImgsUpload from './components/ImgsUpload.vue';
// 导入城市js文件
import cityData from '@/utils/city';
import { getParentCategoriesData, getRootCategoriesData } from '@/api/merchant/merchantAuth';

export default {
  components: {
    ImgsUpload,
  },
  data() {
    return {
      storeAddress: '',
      mainBusinessName: '', // 主营业务，
      ancillaryBusinessName: [], // 辅营业务

      mainBusinessList: [], // 主营业务下拉数组
      ancillaryBusinessList: [], // 辅营业务数组
      storeInfo: {
        region: '',
        storeAddressDetail: '',
        legalRepresentativeName: '',
        mobileNumber: '',
        storeName: '',
        storeImage: '',
        storeInnerImage: [],
        email: '',
        longitude: '',
        latitude: '',
        opening: '',
        city: '',
        province: '',
        district: '',
        mainBusiness: '', // 主营业务，
        ancillaryBusiness: [], // 辅营业务
      },
      rules: {
        opening: {
          type: 'string',
          required: true,
          message: '请输入营业时间',
          trigger: ['blur', 'change'],
        },
        legalRepresentativeName: {
          type: 'string',
          required: true,
          message: '请输入负责人名称',
          trigger: ['blur', 'change'],
        },
        storeName: {
          type: 'string',
          required: true,
          message: '请输入店铺名',
          trigger: ['blur', 'change'],
        },
        storeAddressDetail: {
          type: 'string',
          required: true,
          message: '请输入详细地址',
          trigger: ['blur', 'change'],
        },
        mobileNumber: [
          {
            required: true,
            message: '请输入手机号码',
            trigger: ['blur', 'change'],
          },
          {
            validator: (rule, value, callback) => {
              return uni.$u.test.mobile(value);
            },
            message: '手机号码不正确',
            trigger: ['change', 'blur'],
          },
        ],
        email: [
          {
            required: true,
            message: '请输入您的邮箱',
            trigger: ['blur', 'change'],
          },
          {
            validator: (rule, value, callback) => {
              return uni.$u.test.email(value);
            },
            message: '您输入的邮箱不正确',
            trigger: ['change', 'blur'],
          },
        ],
        region: [
          {
            required: true,
            message: '请选择所在地区',
            trigger: ['change'],
          },
        ],
        mainBusiness: [
          {
            required: true,
            message: '请选择主营业务',
            trigger: ['change'],
          },
        ],
        // ancillaryBusiness: [{
        // 	type: 'string',
        // 	required: true,
        // 	message: '请输入详细地址',
        // 	trigger: ['blur', 'change'],
        // }, ],
      },
      show: false, //显示选择器
      // 打开选择器显示默认城市
      cityList: [], // 选择地区数组
      cityLevel1: [],
      cityLevel2: [],
      cityLevel3: [],

      list: [], // 数组控制器
    };
  },
  onReady() {
    //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
    this.$refs.uForm.setRules(this.rules);
  },
  created() {
    this.request();
  },
  onLoad() {
    if (this.$store.state.data.merchantInfo) {
      console.log(this.$store.state.data.merchantInfo, 'this.$store.state.data.merchantInfo');
      this.storeInfo = {
        region: this.$store.state.data.merchantInfo.merchant.region,
        storeAddressDetail: this.$store.state.data.merchantInfo.storeAddressDetail,
        legalRepresentativeName: this.$store.state.data.merchantInfo.legalRepresentativeName,
        mobileNumber: this.$store.state.data.merchantInfo.mobileNumber,
        storeName: this.$store.state.data.merchantInfo.storeName,
        storeImage: this.$store.state.data.merchantInfo.storeImage,
        storeInnerImage: this.$store.state.data.merchantInfo.storeInnerImage,
        email: this.$store.state.data.merchantInfo.email,
        longitude: this.$store.state.data.merchantInfo.merchant.longitude,
        latitude: this.$store.state.data.merchantInfo.merchant.latitude,
        opening: this.$store.state.data.merchantInfo.merchant.opening,

        city: this.$store.state.data.merchantInfo.merchant.region.toString().slice(0, -2) + '00',
        province:
          this.$store.state.data.merchantInfo.merchant.region.toString().slice(0, -4) + '0000',
        district: this.$store.state.data.merchantInfo.merchant.region,
        mainBusiness: this.$store.state.data.merchantInfo.merchant.mainBusiness, // 主营业务，
        ancillaryBusiness: this.$store.state.data.merchantInfo.merchant.ancillaryBusiness, // 辅营业务
      };
      this.storeAddress = this.findAreaByCode(this.$store.state.data.merchantInfo.merchant.region);
    }
  },
  onShow() {
    this.initCityData();
  },

  methods: {
    async request() {
      const res = await getParentCategoriesData({
        type: '0',
      });
      this.mainBusinessList = res.data.map(item => {
        return {
          name: item.name,
          id: item.id,
        };
      });
      const res1 = await getRootCategoriesData({
        type: '0',
      });
      this.ancillaryBusinessList = res1.data.map(item => {
        return {
          name: item.name,
          id: item.id,
          status: 1,
        };
      });
      if (this.$store.state.data.merchantInfo) {
        this.mainBusinessName = this.nameFunction(
          [this.$store.state.data.merchantInfo.merchant.mainBusiness],
          this.mainBusinessList,
        );
        this.ancillaryBusinessName = this.nameFunction(
          this.$store.state.data.merchantInfo.merchant.ancillaryBusiness,
          this.ancillaryBusinessList,
        );
      }

      console.log(this.ancillaryBusinessList, '这是请i去的');
    },
    // 手动选择城市
    manualGetLocation() {
      uni.chooseLocation({
        success: res => {
          console.log(res, '点击获取的');
          let { longitude, latitude } = res;
          console.log(this.stereInfo, 'this');
          this.storeInfo.longitude = parseFloat(longitude.toFixed(5));
          this.storeInfo.latitude = parseFloat(latitude.toFixed(5));
          this.storeInfo.storeAddressDetail = res.address;
        },
        fail: err => {},
      });
    },
    initCityData() {
      // 遍历城市js
      cityData.forEach((item1, index1) => {
        let temp2 = [];
        this.cityLevel1.push({
          name: item1.provinceName,
          id: item1.provinceCode,
        });

        let temp4 = [];
        let temp3 = [];
        // 遍历市
        item1.cities.forEach((item2, index2) => {
          temp2.push({
            name: item2.cityName,
            id: item2.cityCode,
          });
          // 遍历区
          item2.counties.forEach((item3, index3) => {
            temp3.push({
              name: item3.countyName,
              id: item3.countyCode,
            });
          });
          temp4[index2] = temp3;
          temp3 = [];
        });
        this.cityLevel3[index1] = temp4;
        this.cityLevel2[index1] = temp2;
      });
      // 选择器默认城市
      this.cityList.push(this.cityLevel1, this.cityLevel2[0], this.cityLevel3[0][0]);
      console.log(this.cityList, 'this.cityList');
    },
    // 选中时执行
    changeHandler(e) {
      if (this.list.length > 1) {
        const {
          columnIndex,
          index,
          indexs,
          value,
          values,
          // 微信小程序无法将picker实例传出来，只能通过ref操作
          picker = this.$refs.uPicker,
        } = e;
        if (columnIndex === 0) {
          // 选择第一列数据时 设置第二列关联数据
          picker.setColumnValues(1, this.cityLevel2[index]);
          // 设置第三列关联数据
          picker.setColumnValues(2, this.cityLevel3[index][columnIndex]);
        } else if (columnIndex === 1) {
          // 选择第二列数据时 设置第三列关联数据
          picker.setColumnValues(2, this.cityLevel3[indexs[0]][index]);
        }
      }
    },
    // 单击确认按钮时执行
    confirm(e) {
      if (e.value.length > 1) {
        this.storeInfo.province = parseInt(e.value[0].id, 10);
        this.storeInfo.city = parseInt(e.value[1].id, 10);
        this.storeInfo.district = parseInt(e.value[2].id, 10);
        this.storeInfo.region = parseInt(e.value[2].id, 10);
        this.storeAddress = e.value.map(item => item.name).join('');
        // 隐藏城市选择器
      } else {
        if (e.value[0].status && e.value[0].status == 1) {
          this.ancillaryBusinessName.push(e.value[0].name);
          this.storeInfo.ancillaryBusiness.push(e.value[0].id);
        } else {
          this.mainBusinessName = e.value[0].name;
          this.storeInfo.mainBusiness = e.value[0].id;
        }
      }
      this.show = false;
    },
    // 点击选择地区
    handlerChange() {
      this.list = this.cityList;
      this.show = true;
    },
    //点击选择主营业务
    handlerChangeMainBusiness() {
      this.list = [this.mainBusinessList];
      this.show = true;
    },
    //点击选择辅营业务
    handlerChangeAncillaryBusiness() {
      console.log('asdsd');
      this.list = [this.ancillaryBusinessList];
      console.log(this.list);
      this.show = true;
    },
    //点击清空按钮
    ancillaryBusinessClear() {
      this.ancillaryBusinessName = [];
      this.storeInfo.ancillaryBusiness = [];
    },
    handlerSkipNext() {
      this.$refs.uForm.validate().then(res => {
        this.$store.commit('SET_STOREINFO', this.storeInfo);
        setTimeout(() => {
          uni.navigateTo({
            url: '/pageMerchant/mineModule/certification/corporateInformation',
          });
        }, 1500);
      });
    },
    // 图片
    fileList(val, data) {
      console.log(data, 'data');
      if (data == 1) {
        this.storeInfo.storeImage = val[0];
      } else if (data == 2) {
        this.storeInfo.storeInnerImage = val.map(item => {
          return {
            url: item,
            media: 'IMAGE',
          };
        });
      }
    },

    //回显时展示的
    nameFunction(idArray, services) {
      let nameString = '';
      if (idArray.length > 1) {
        nameString = idArray
          .map(id => services.find(service => service.id == id))
          .filter(service => service)
          .map(service => service.name);
      } else {
        nameString = idArray
          .map(id => services.find(service => service.id == id))
          .filter(service => service)
          .map(service => service.name)
          .join(',');
      }
      return nameString;
    },
    findAreaByCode(areaCode) {
      for (const province of cityData) {
        if (province.provinceCode == areaCode) {
          return `${province.provinceName}`;
        }
        for (const city of province.cities) {
          if (city.cityCode == areaCode) {
            return `${province.provinceName} - ${city.cityName}`;
          }
          const county = city.counties.find(item => item.countyCode == areaCode);
          if (county) {
            return `${province.provinceName}  ${city.cityName}  ${county.countyName}`;
          }
        }
      }
      return '未找到对应地区';
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  background-color: #f7f7f7 !important;
  padding-bottom: 40rpx;

  .top-box {
    color: #666666;
    font-size: 26rpx;
    text-align: center;
    padding: 20rpx 40rpx;
    background-color: #fff;
  }

  .content-box {
    padding: 20rpx 40rpx;
    background-color: #fff;
    margin: 10rpx 0;

    .content-item {
      position: relative;

      .item-r {
        background-color: #f7f7f7;
        border-radius: 20rpx;
        display: flex;

        .data_select {
          width: 90%;
        }

        ::v-deep .u-form-item {
          width: 100%;
        }

        ::v-deep .u-form-item__body {
          padding: 0;
        }
      }

      .icon-right-box {
        position: absolute;
        right: 15rpx;
        top: 40rpx;
      }
    }

    .upload-text {
      text-align: center;
      color: #666666;
      font-size: 28rpx;
      margin-top: 20rpx;
    }
  }

  .btn {
    background-color: #5992bb !important;
    color: #fff;
    font-size: 32rpx;
    border-radius: 40rpx;
    margin-top: 100rpx;
    margin-bottom: 100rpx;
    width: 95%;
  }
}

::v-deep .uni-select {
  border: none !important;
}

::v-deep .uni-select__input-placeholder {
  font-size: 28rpx !important;
  color: #cbced4 !important;
}
</style>