<template>
  <view class="app-wallpaper" :style="{padding:paddingTop?'16rpx 26rpx':'0rpx 26rpx 16rpx 26rpx'}">
    <view class="fxx-container row">
      <view class="fxx-content">
        <u-form errorType="toast" labelPosition="left" :model="model" :rules="rules" ref="authForm"
                labelWidth="160rpx" label-style="font-size:32rpx;color:#020B18;">
          <u-form-item prop="userInfo.sex" :custom-style="{padding:'34rpx 0'}">
            <!--#ifdef MP-WEIXIN-->
            <button open-type="chooseAvatar" @chooseavatar="uploadAvatar" class="avatarBtn"
                    style="background:transparent;">
              <view class="" style="margin:auto;position: relative">
                <u-avatar :src="model.userInfo.avatar" size="160"
                          custom-style="margin:auto;"></u-avatar>
                <view class="camera" style="position:absolute;right:0;bottom:0">
                  <u-image :src="staticImage.camera" width="64" height="64"></u-image>
                </view>
              </view>
            </button>
            <!--#endif-->
            <!--#ifdef H5-->
            <button @click="chooseAvatar" class="avatarBtn"
                    style="background:transparent;">
              <view class="" style="margin:auto;position: relative">
                <u-avatar :src="model.userInfo.avatar" size="160"
                          custom-style="margin:auto;"></u-avatar>
                <view class="camera" style="position:absolute;right:0;bottom:0">
                  <u-image :src="staticImage.camera" width="64" height="64"></u-image>
                </view>
              </view>
            </button>
            <!--#endif-->
          </u-form-item>
          <u-form-item required :custom-style="{
                  padding:'36rpx 0'
              }" label="主体" prop="userInfo.body" borderBottom>
            <u-radio-group v-model="model.userInfo.principal_part" placement="row" @change="bodyChange">
              <u-radio size="32" labelSize="32" icon-size="24" activeColor="#FF9545"
                       :customStyle="{marginRight: '50rpx'}" v-for="(item, index) in bodyList" :key="index"
                       :label="item.name" :name="item.id">
              </u-radio>
            </u-radio-group>
          </u-form-item>
          <u-form-item required :custom-style="{
                  padding:'36rpx 0'
              }" :label="model.userInfo.principal_part === 2?'联系人':'姓名'" prop="userInfo.name" borderBottom>
            <u-input fontSize="28" placeholder="请填写您的真实姓名" v-model="model.userInfo.name"
                     border="none"></u-input>
          </u-form-item>
          <u-form-item required :custom-style="{
                  padding:'36rpx 0'
              }" label="性别" prop="userInfo.sex" borderBottom>
            <u-radio-group v-model="model.userInfo.sex" placement="row" @change="sexChange">
              <u-radio size="32" labelSize="32" icon-size="24" activeColor="#FF9545"
                       :customStyle="{marginRight: '80rpx'}" v-for="(item, index) in sexList" :key="index"
                       :label="item.name" :name="item.id">
              </u-radio>
            </u-radio-group>
          </u-form-item>
          <u-form-item required v-if="model.userInfo.principal_part === 2" :custom-style="{
                  padding:'36rpx 0'
              }" label="公司名称" prop="userInfo.company" borderBottom>
            <u-input fontSize="28" placeholder="请填写公司全称" v-model="model.userInfo.company"
                     border="none"></u-input>
          </u-form-item>
          <u-form-item required :custom-style="{
                  padding:'36rpx 0'
              }" label="手机号码" prop="userInfo.phone" borderBottom>
            <u-input fontSize="28" placeholder="请输入" v-model="model.userInfo.phone" border="none"></u-input>
          </u-form-item>
          <u-form-item required :custom-style="{
                  padding:'36rpx 0'
              }" label="现住地" prop="userInfo.address" borderBottom>
            <u-input fontSize="28" placeholder="请输入" v-model="model.userInfo.address"
                     border="none"></u-input>
          </u-form-item>
          <u-form-item required :custom-style="{
                  padding:'36rpx 0'
              }" label="邮箱" prop="userInfo.email" borderBottom>
            <u-input fontSize="28" placeholder="请输入" v-model="model.userInfo.email" border="none"></u-input>
          </u-form-item>
          <u-form-item required :custom-style="{
                  padding:'36rpx 0'
              }" label="所属街道" prop="userInfo.street_id" borderBottom>
            <u-text @click="openStreetPicker" :text="model.userInfo.street_name||'请选择'" size="28"
                    :color="model.userInfo.street_name?'#020B18':'#AFB5BE'" suffixIcon="arrow-right"
                    :icon-style="{color:(model.userInfo.street_name?'#020B18':'#AFB5BE')}"></u-text>
          </u-form-item>
          <u-form-item required :custom-style="{
                  padding:'36rpx 0'
              }" label="所属社区" prop="userInfo.community" borderBottom>
            <u-text @click="openCommunityPicker" :text="model.userInfo.community_name||'请选择'" size="28"
                    :color="model.userInfo.community_name?'#020B18':'#AFB5BE'" suffixIcon="arrow-right"
                    :icon-style="{color:(model.userInfo.community_name?'#020B18':'#AFB5BE')}"></u-text>
          </u-form-item>

          <u-form-item required :custom-style="{
                  padding:'36rpx 0'
              }" label="顾问类别" prop="userInfo.advisor_type " borderBottom>
            <view class="advisorType">

              <view class="tags row" v-if="advisor_type?.length > 0" style="align-items: center;">
                <view class="tag" v-for="(item,index) in advisor_type">
                  <uv-tags closable type="warning" :text="item.label" @close="delAdvisorType(index)"></uv-tags>
                </view>
                <view class="" style="padding-top: 30rpx;">
                  <u-text @click="openAdvisorPicker" text="" size="28" color="#AFB5BE" suffixIcon="arrow-right"
                          icon-style="color:#AFB5BE;"></u-text>
                </view>
              </view>
              <view class="tags" v-else>
                <u-text @click="openAdvisorPicker" text="请选择" size="28" color="#AFB5BE" suffixIcon="arrow-right"
                        icon-style="color:#AFB5BE;"></u-text>
              </view>
            </view>


          </u-form-item>

          <u-form-item :custom-style="{
                  padding:'36rpx 0'
              }" prop="userInfo.infomation" borderBottom>
            <view class="row" style="margin-bottom:22rpx;">
              <view style="max-width:25px;">
                <u-text text="*" size="20px"
                        color="#f56c6c"></u-text>
              </view>
              <u-text text="顾问介绍" size="32"
                      color="#020B18"></u-text>
            </view>
            <u-textarea v-model="model.userInfo.infomation" border="none" placeholder="请输入个人履历及服务擅长项"
                        height="220" :custom-style="{
                backgroundColor:'#FAFAFA',
                padding:'20rpx'
              }"></u-textarea>
          </u-form-item>
          <u-form-item prop="userInfo.sex" :custom-style="{padding:'34rpx 0'}">
            <view class="row" style="margin-bottom:22rpx;">
              <view style="max-width:25px;">
                <u-text text="*" size="20px"
                        color="#f56c6c"></u-text>
              </view>
              <u-text text="资料上传" size="32"
                      color="#020B18"></u-text>
            </view>
            <uv-upload width="160ropx" height="160rpx" :fileList="images.aptitude" name="1" multiple
                       :maxCount="10" uploadIcon="plus" @delete="(res) => {uploadDel(res,'aptitude')}"
                       @afterRead="(res) => {uploadPut(res,'aptitude')}"></uv-upload>
          </u-form-item>

        </u-form>

      </view>
    </view>
    <view class="foot-button border-box">
      <u-button type="primary" :text="isEdit?'保存':'立即认证'" shape="circle" :custom-style="{
              color:'#020B18',
              backgroundColor:'#FF9545',
              border:'none',
              fontSize:'36',
              fontWeight:'400',
            }" @click="submit"></u-button>
    </view>
    <uv-picker ref="street" :columns="[streetList]" keyName="name" @confirm="selectStreet"></uv-picker>
    <uv-picker ref="community" :columns="[communityList]" keyName="name" @confirm="selectCommunity"></uv-picker>
    <uv-picker ref="advisor" :columns="[advisorTypeList]" keyName="label" @confirm="selectAdvisor"></uv-picker>

    <uv-popup ref="advisorPopup" mode="bottom" round="10rpx" closeable safeAreaInsetTop safeAreaInsetBottom
              custom-style="position:relative;">
      <view class="title row" style="position:absolute;justify-content: center;width:100%;top:20rpx;left:0;">
        <view class="value col" style="position: relative;text-align: center;">

          <!--        <u-text text="协议内容" size="38" color="#191919"></u-text>-->
          <view class="" style="position: relative;display:inline-block;">
            <view style="color:#191919;font-size:38rpx;display:inline-block;position: relative;z-index: 2;">
              选择顾问类型
            </view>
            <!--            <view class="background" style="width:100%;height:50%;position: absolute;bottom:0;left:0;background-color:rgba(227, 191, 119, 0.6);display:inline-block;z-index:1;"></view>-->
          </view>
        </view>
      </view>
      <view class="pop-service-container" style="min-height:500rpx;position:relative;">
        <view class="" style="width:100%;padding-bottom:114rpx;">
          <u-cell-group custom-style="max-height:700rpx;overflow:auto;" v-if="advisorTypeList.length">
            <u-cell
                size="large"
                :title="item.label"
                isLink
                right-icon=""
                @click="selectAdvisor(index)"
                v-for="(item,index) in advisorTypeList">
              <template #value>
                <view class="">
                  <view class="" style="display:flex;align-items: center">
                    <view class="">
                      <u-checkbox-group @change="typeCheckChange">
                        <u-checkbox :name="index"
                                    :customStyle="{marginBottom: '0',marginTop: '0',marginLeft:'15rpx'}"
                                    size="32" :checked="item.checked" activeColor="#FF9545"
                                    iconSize="30">
                        </u-checkbox>
                      </u-checkbox-group>
                    </view>
                  </view>
                </view>
              </template>
            </u-cell>
          </u-cell-group>
          <u-cell-group custom-style="max-height:700rpx;overflow:auto;" v-else>
            <u-cell size="large" title="暂无">
            </u-cell>
          </u-cell-group>
        </view>
        <view class="row" style="position:absolute;bottom:0;width:100%;padding-top:30rpx;" v-if="true">
          <view class="col-6" style="padding:0 30rpx;'">
            <u-button text="取消" @click="$refs.advisorPopup.close()"></u-button>
          </view>
          <view class="col-6" style="padding:0 30rpx;">
            <u-button color="#FF9545" text="确认" @click="advisorConfirm"
                      custom-style="color:#020B18;"></u-button>
          </view>
        </view>
      </view>
    </uv-popup>
  </view>
</template>

<script>
import {imghost} from '@/config/host.js'
import MzSubsection from '@/components/MzSubsection/Index.vue';
import api from '@/utils/functions.js';
import {getCommonStreet, systemConfig} from "@/api/other";
import {avatarUpload, userExtends} from "@/api/user";
import {setAdvisor} from "@/api/advisor";

export default {
  components: {
    MzSubsection
  },
  props: {
    paddingTop: {
      type: Boolean,
      default: true,
    },
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      polShow: false,
      advisor_type: [],
      model: {
        userInfo: {
          name: '',
          avatar: '',
          sex: 1,
          principal_part: 1,
          phone: '',
          company: '',
          address: '',
          street_id: '',
          community_id: '',
          community_name: '',
          street_name: '',
          email: '',
          advisor_type: '',
          infomation: '',
          aptitude: [],
        },
      },
      images: {
        aptitude: [],
      },
      rules: {
        'userInfo.principal_part': {
          type: 'number',
          required: true,
          message: '请选择主体',
          trigger: ['blur', 'change']
        },
        'userInfo.avatar': {
          type: 'number',
          required: true,
          message: '请选择头像',
          trigger: ['blur', 'change']
        },
        'userInfo.name': {
          type: 'string',
          required: true,
          message: '请填写姓名',
          trigger: ['blur', 'change']
        },
        'userInfo.sex': {
          type: 'string',
          max: 1,
          required: true,
          message: '请选择男或女',
          trigger: ['blur', 'change']
        },
        'userInfo.phone': {
          type: 'string',
          required: true,
          message: '请输入手机号码',
          trigger: ['blur', 'change']
        },
        'userInfo.street_id': {
          type: 'string',
          required: true,
          message: '请选择街道',
          trigger: ['blur', 'change']
        },
        'userInfo.community_id': {
          type: 'string',
          required: true,
          message: '请选择社区',
          trigger: ['blur', 'change']
        },
        'userInfo.advisor_type': {
          type: 'string',
          required: true,
          message: '请选择顾问类型',
          trigger: ['blur', 'change']
        },
        'userInfo.infomation': {
          type: 'string',
          required: true,
          message: '请输入介绍',
          trigger: ['blur', 'change']
        },
      },
      sexList: [{
        id: 1,
        name: '男',
        disabled: false,
      },
        {
          id: 2,
          name: '女',
          disabled: false,
        },
      ],
      bodyList: [{
        id: 1,
        name: '个人',
        disabled: false,
      },
        {
          id: 2,
          name: '公司或组织',
          disabled: false,
        },
      ],
      political_outlook_name: '',
      current: 1,
      title: '顾问认证',
      loading: true,
      staticImage: {
        bg: imghost + '/BG.png',
        newIcon: imghost + '/new-icon.png',
        fxxLogo: imghost + '/fxx-logo.png',
        fxx1: imghost + '/fxx-1.png',
        camera: imghost + '/camera.png',
      },
      user: {
        avatar: imghost + '/banner.png',
        nickname: '清晨的风',
        coupons: 221,
        id: 88685,
      },
      isTop: false,
      size: {
        height: 500,
      },
      streetList: [],
      communityList: [],
      positionList: [],
      advisorTypeList: [],
    }
  },
  methods: {
    delAdvisorType(index) {
      this.advisor_type.splice(index, 1)
    },
    advisorConfirm() {
      let list = [];
      this.advisorTypeList.map(item => {
        if (item.checked) {
          list.push(item);
        }
      });
      this.advisor_type = list;
      this.$refs.advisorPopup.close();
    },
    typeCheckChange(e) {
      this.advisorTypeList[e].checked = !this.advisorTypeList[e].checked;
    },
    selectAdvisor(index) {
      this.advisorTypeList[index].checked = !this.advisorTypeList[index].checked;
    },
    uploadAvatar(e) {
      console.log(e)
      api.uploadOssFile(e.detail.avatarUrl).then(res => {
        this.model.userInfo.avatar = res.show_path
        avatarUpload({
          url: res.show_path
        }).then(res => {
          if (res.code === 200) {
            uni.$u.toast('修改成功')
          } else {
            uni.$u.toast(res.msg)
          }
        }).catch(err => {
          uni.$u.toast('服务器开小差了')
        })
      })
    },
    uploadSubmit(data, fileName = '') {
      this.model.userInfo[fileName] = data.map(item => {
        return item.url;
      })
    },
    uploadShow(data, fileName = '') {
      let result = [];
      try {
        data.forEach(item => {
          result.push({
            url: item.url
          })
        })
      } catch (e) {
        this.images[fileName] = [];
      }
      this.images[fileName] = result;
    },
    uploadPut(event, fileName = '') {
      let lists = [].concat(event.file);
      let fileListLen = this.images[fileName].length;
      lists.map((item) => {
        this.images[fileName].push({
          ...item,
          status: 'uploading',
          message: '上传中',
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const fileType = api.getFileType(lists[i].url);
        console.log(fileType)
        api.uploadOssFile(lists[i].url).then(res => {
          let item = this.images[fileName][fileListLen];
          this.images[fileName].splice(fileListLen, 1, {
            ...item,
            status: 'success',
            message: '',
            url: res.show_path,
            thumb: res.show_path,
            type: fileType
          });
          fileListLen++;
        })
      }
    },
    uploadDel(fileIndex, fileName = '') {
      this.images[fileName].splice(fileIndex.index, 1);
    },
    openPolPicker() {
      this.$refs.pol.open();
    },
    openStreetPicker() {
      this.$refs.street.open();
    },
    openCommunityPicker() {
      this.$refs.community.open();
    },
    openPositionPicker() {
      this.$refs.position.open();
    },
    openAdvisorPicker() {
      if (this.advisor_type?.length > 0) {
        const checkedValue = this.advisor_type.map(item => {
          return item.value;
        });
        this.advisorTypeList.map(item => {
          if (checkedValue.indexOf(item.value) !== -1) {
            item.checked = true;
          } else {
            item.checked = false;
          }
        })
      }
      this.$refs.advisorPopup.open();
    },
    chatDetail(item) {
      wx.navigateTo({
        url: '/pages/ChatDetail/index?id=' + item.id
      });
    },
    checkSection(index) {
      this.current = index;
    },
    scrollToLower() {

    },
    sexChange(e) {
      console.log(e)
      this.model.userInfo.sex = e;
    },
    bodyChange(e) {
      z
      console.log(e)
      this.model.userInfo.principal_part = e;
    },
    navTo(url) {
      uni.navigateTo({
        url: url
      })
    },
    getPickerData() {
      systemConfig({
        type: 'advisor_type'
      }).then(res => {
        this.advisorTypeList = res.data.map(item => {
          item.checked = false;
          return item;
        });
      })
      getCommonStreet({}).then(res => {
        this.streetList = res.data
      });
    },
    selectPol(e) {
      this.political_outlook_name = e.value[0].name;
      this.model.userInfo.political_outlook = e.value[0].id;
      this.polShow = false;
    },
    selectStreet(e) {
      this.model.userInfo.street_id = e.value[0].id;
      this.model.userInfo.street_name = e.value[0].name;
      this.communityList = e.value[0].children;
    },
    selectCommunity(e) {
      this.model.userInfo.community_name = e.value[0].name;
      this.model.userInfo.community_id = e.value[0].id;
    },
    selectPosition(e) {
      this.model.userInfo.position_type = e.value[0].name;
    },
    submit() {
      this.uploadSubmit(this.images.aptitude, 'aptitude');
      this.model.userInfo.advisor_type = this.advisor_type.map(item => {
        return item.value;
      }).join(',');
      setAdvisor(this.model.userInfo).then(res => {
        if (res.code === 200) {
          if (!this.isEdit) {
            this.navTo('/pages/Consultant/done?name=' + this.model.userInfo.name)
          } else {
            api.success('修改成功').then(() => {
              uni.navigateBack();
            });
          }
        } else {
          uni.$u.toast(res.msg);
        }
      })

    },
    getUserExtend() {
      userExtends().then((res) => {
        if (res.code === 200) {
          if (res.data.advisor?.id) {
            this.model.userInfo = res.data.advisor;
            this.model.userInfo.name = res.data.advisor.name;
            this.model.userInfo.principal_part = res.data.advisor.principal_part;
            this.model.userInfo.sex = res.data.advisor.sex;
            this.model.userInfo.phone = res.data.advisor.phone;
            this.model.userInfo.address = res.data.advisor.address;
            this.model.userInfo.community_name = res.data.advisor.community;
            this.model.userInfo.street_name = res.data.advisor.street;
            this.model.userInfo.advisor_type = res.data.advisor.type;
            this.uploadShow(res.data.advisor.aptitude, 'aptitude');
            this.advisor_type = res.data.advisor.type_name || [];
          } else {
            this.userInfo = res.data;
            this.model.userInfo.name = res.data.name;
            this.model.userInfo.phone = res.data.phone;
            this.model.userInfo.company = res.data.company;
          }
        }
      });
    },
    //#ifdef H5
    chooseAvatar() {
      let that = this;
      uni.chooseImage({
        count: 1, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album'], //从相册选择
        success: function (res) {
          console.log('res',res)
          that.uploadAvatar({detail: {avatarUrl: res.tempFilePaths}});
        }
      });
    },
    pickExclude(obj, keys) {
      // 某些情况下，type可能会为
      if (!['[object Object]', '[object File]'].includes(Object.prototype.toString.call(obj))) {
        return {}
      }
      return Object.keys(obj).reduce((prev, key) => {
        if (!keys.includes(key)) {
          prev[key] = obj[key]
        }
        return prev
      }, {})
    },
    formatImage(res) {
      let that = this;
      return res.tempFiles.map((item) => ({
        ...that.pickExclude(item, ['path']),
        type: 'image',
        url: item.path,
        thumb: item.path,
        size: item.size,
        // #ifdef H5
        name: item.name
        // #endif
      }))
    }
    //#endif
  },
  mounted() {
    this.getPickerData();
    let token = uni.getStorageSync('token');
    if (token) {
      this.getUserExtend();
    }
  },
}
</script>

<style lang="scss">
@import './components/index.scss';
</style>