<template>
  <view>
    <!-- 导航栏 -->
    <u-navbar :background="{ background: '#f5f5f5' }" back-icon-color="#000000" title-color="#000000"
      :border-bottom="false" :title="type?'编辑地址':'新增地址'">
      <view @tap="delshow=true" v-if="type"  class="pl-base text-lg ">
        删除
      </view>
    </u-navbar>
    <view class="w-full  bg-white box-shadow p-base ">
      <u-form :label-style="labelstyle" :model="form" ref="uForm" :error-type="['toast']">
        <u-form-item prop="consignee" label="收货人" label-width="220">

          <input placeholder-class="placeholder" :adjust-position="false" class="w-full h-full" type="text"
            v-model="form.consignee" placeholder="请填写收件人名称">
        </u-form-item>
        <u-form-item prop="telephone" label="电话" label-width="220">
          <input maxlength="11" placeholder-class="placeholder" :adjust-position="false" class="w-full h-full" type="number"
            v-model="form.telephone" placeholder="请填写联系方式">

        </u-form-item>
        <u-form-item prop="zone" label="所在地区" label-width="220">
          <view class="flex items-center justify-between w-full">
            <view @tap="show=true" class="flex-1 text-md" :class="form.zone?'':'text-hex-c0c4cc'">
               {{form.zone?form.zone:'请选择地区'}}
             </view>
            <!-- <u-input :adjust-position="false" @tap="show=true" :clearable="false" v-model="form.zone"
               placeholder="请选择地区" disabled/> -->
             <view @tap="getJudgeMap" class="flex items-center text-md text-txBase">
               <view>定位</view>
               <u-icon name="map" color="#000000" size="36"></u-icon>
             </view>
          </view>
          <!-- 弹窗 -->
          <u-select :default-value="defaultValue" value-name="id" label-name="name" mode="mutil-column-auto"
            @confirm="regConfirm" confirm-color="#378264" v-model="show" :list="regList"></u-select>
        </u-form-item>
        <u-form-item prop="address" label="详细地址" label-width="220">
          <input placeholder-class="placeholder" :adjust-position="false" class="w-full h-full" type="text"
            v-model="form.address" placeholder="请填写详细地址">
          <!-- <u-input :adjust-position="false"  :clearable="false" v-model="form.address" placeholder="请填写详细地址" /> -->
        </u-form-item>
        <u-form-item label="设为默认地址" label-width="220" :border-bottom="false">
          <u-switch inactive-color="#808080" active-color="#378264" slot="right" v-model="form.is_default"></u-switch>
        </u-form-item>
      </u-form>
    </view>
     <view class=" text-txGray text-md mt-46rpx px-base">提示：请认真填写收货地址，避免寄送发生错误</view>
    <view class="mt-200rpx px-base">
      <view class="login-btn" @tap="onSubmit"> 保存地址 </view>
    </view>
    <cu-modal v-model="delshow"   @confirm="confirm" confirm-color="#378264" show-cancel-button
      content="是否确认删除"></cu-modal>
      <cu-modal title="提示" v-model="showModel" content="没有开启定位权限,点击确定授权" confirm-color="#378264" show-cancel-button
        @confirm="onConfirm"></cu-modal>
  </view>
</template>

<script>
  import { getTreeData } from '@/utils'
  import addressParse from '@/utils/address_parse'
  export default {

    data() {
      return {
        showModel: false,
        form: {
          consignee: '', //收件人
          telephone: '', //电话
          zone_id: '', //地区id
          zone: '', //所在地区文字
          address: '', //详细地址
          is_default: false, //是否默认
          id: '',
        },
        rules: {
          consignee: [{
            required: true,
            message: '请填写收件人',
            trigger: 'change',
          }, ],
          telephone: [{
              required: true,
              message: '请输入手机号',
              trigger: 'change',
            },
            {
              validator: (rule, value, callback) => {
                return this.$u.test.mobile(value);
              },
              message: '手机号码不正确',
              trigger: 'change',
            },
          ],
          zone: [{
            required: true,
            message: '请选择所在地',
            trigger: 'blur',
          }, ],
          address: [{
            required: true,
            message: '请填写详细地址',
            trigger: 'change',
          }, ],
        },

        show: false,
        labelstyle: {
          fontSize: '30rpx',
          color: '#383838'
        },
        regList: [], //地区数据
        defaultValue: [0, 0, 0], //地区默认选中
        type: false, //判断是编辑地址还是新增地址
        delshow:false,
        addressType:''
      };
    },
    onReady() {
      this.$refs.uForm.setRules(this.rules);
    },
    async onLoad({
      info,
      addressType
    }) {
      if (info) {
        this.type = true
        let item = JSON.parse(info)
        this.form.consignee = item.consignee
        this.form.is_default = item.is_default
        this.form.telephone = item.telephone
        this.form.zone = item.zone
        this.form.zone_id = item.zone_id
        this.form.address = item.address
        this.form.id = item.id
      }
      this.addressType = addressType
      await this.getRegion()
    },
    methods: {
      onMap(){
        uni.chooseLocation({
            success: (res) => {
              // console.log(res);
              if(res.name=='') return
              const addr = addressParse(res.address,this.regList)
              // console.log(addr);
              const locat = [{
                value:addr.provinceCode,
                label:addr.province
              },{
                value:addr.cityCode,
                label:addr.city
              },{
                value:addr.areaCode,
                label:addr.area
              }].filter(({value})=>!!value)
              this.defaultValue = this.treeFindPath(this.regList,node => node.id === locat[locat.length-1].value)
              this.form.zone_id = locat[locat.length-1].value
              this.form.zone = locat.map(({label})=>label).join(' ')
              this.form.address = addr.address
            }
        });
      },
      // 开始
      //判断小程序定位权限是否开启
      getJudgeMap(){
        uni.authorize({
           scope: 'scope.userLocation',
          success: async res => {
            await this.onMap()
          },
          fail: (comp) => {
            uni.getSetting({
              success: Setting => {
                if (!Setting.authSetting['scope.userLocation']) {
                  this.showModel = true
                }
              }
            });
          }
        })
      },
      onConfirm() {
        this.showModel = false
        uni.openSetting({
          success: res => {
          },
        });
      },
      //结束
      //获取地区
      async getRegion() {
        let res = await this.$api.get('/v1/zones');
        this.regList = getTreeData(res, null, 'parent_id', 'id', 'children', 'code')
        this.defaultValue = this.treeFindPath(this.regList,node => node.id === this.form.zone_id)
      },
      //选择的地区
      regConfirm(e) {
        this.form.zone_id = e[2].value
        this.form.zone = e[0].label + ' ' + e[1].label + ' ' + e[2].label
        this.defaultValue = this.treeFindPath(this.regList,node => node.id === e[2].value)
      },
      treeFindPath (tree, func, path = []) {
        if (!tree) return []
        let i = 0
        for (const data of tree) {


          path.push(i)
          if (func(data)) return path
          i++
          if (data.children) {
            const findChildren = this.treeFindPath(data.children, func, path)
            if (findChildren.length) return findChildren
          }
          path.pop()
        }
        return []
      },

      confirm(){
        try{
          this.$api.delete(`/v1/shipping-addresses/${this.form.id}`, {}, {
            custom: {
              loading: true
            },
          });
          this.$u.toast("删除成功")
          this.type = false
          uni.navigateBack()
        }catch(err){}
      },
      //提交
      onSubmit() {
        this.$refs.uForm.validate(async (valid) => {
          if (valid) {
            try {
              let obj = {
                consignee: this.form.consignee,
                telephone: this.form.telephone,
                zone_id: this.form.zone_id,
                address: this.form.address,
                is_default: this.form.is_default
              }
              //新增
              if (!this.type) {
                let res = await this.$api.post('/v1/shipping-addresses', obj, {
                  custom: {
                    loading: true
                  },
                });
                if(this.addressType=='select') uni.$emit('address:select', res)

              } else {
                //修改
                let res = await this.$api.put(`/v1/shipping-addresses/${this.form.id}`, obj, {
                  custom: {
                    loading: true
                  },
                });
              }

              this.$u.toast("保存成功")
              this.$refs.uForm.resetFields()
              this.type = false
              uni.navigateBack()
            } catch (error) {
              // console.log(error);
            }
          }
        });
      }
    }
  }
</script>

<style lang="scss">
  .box-shadow {
    box-shadow: 0px 2rpx 4rpx rgba(0, 0, 0, 0.13);
    border-radius: 15rpx;
  }

  .placeholder {
    color: #c0c4cc;
  }
</style>
