<!--todo 页面逻辑重新过滤-->
<!-- 完善信息 -->
<template>
  <view>
    <view class="body" :style="{ bottom: footerHeight + 'px'}">
      <!-- 操作step -->
      <view class="u-p-30">
        <steps :list="steps" :current="current"></steps>
      </view>
      <!-- 身份选择 -->
      <view v-if="current === 0">
        <view class="u-p-30">
          <user-select :list="userSelect" @change="userSelectCallback"></user-select>
        </view>
      </view>
      <!-- 完善信息 -->
      <view v-if="current === 1">
        <!-- 面料供应商 -->
        <template v-if="assignType === 1">
          <u-form labelWidth="100" labelPosition="top" class="bg-fff">
            <u-form-item label="企业名称" class="u-border-bottom u-p-t-24 u-p-r-30 u-p-b-24 u-p-l-30" :style="style">
              <u-input v-model="formData.enterpriseName" :border="false"  placeholder="请输入企业名称" />
            </u-form-item>
            <u-form-item label="企业联系人" class="u-border-bottom u-p-t-24 u-p-r-30 u-p-b-24 u-p-l-30" :style="style">
              <u-input v-model="formData.corporateContactName" :border="false"  placeholder="请输入企业联系人" />
            </u-form-item>
<!--            <u-form-item label="档口地址" class="u-border-bottom u-p-t-24 u-p-r-30 u-p-b-24 u-p-l-30" :style="style">-->
<!--              <u-input v-model="formData.institutionAddress" :border="false"  placeholder="请输入档口地址" />-->
<!--            </u-form-item>-->
          </u-form>
          <view class="u-p-t-24 u-p-r-30 u-p-b-24 u-p-l-30 u-m-b-30 u-m-t-30 bg-fff">
            <u-collapse accordion>
              <u-collapse-item v-for="(item,index) in subsidiaryInfo" :key="index">
                <view slot="title">
                  <text class="u-page__item__title__slot-title">档口{{ index + 1 }}</text>
                  <text @click.stop="delSubsidiaryInfoRow(item,index)">删除</text>
                </view>

                <view class="u-collapse-content">
                  <u-form labelWidth="100" labelPosition="top" >
                    <u-form-item label="档口名称" :style="style">
                      <u-input v-model="item.stallName" :border="false" placeholder="请输入档口名称" />
                    </u-form-item>
                    <u-form-item label="档口地址" :style="style">
                      <u-input v-model="item.stallAddress" :border="false" placeholder="请输入档口地址"
                              />
                    </u-form-item>
                  </u-form>
                </view>
              </u-collapse-item>
            </u-collapse>
          </view>

          <u-button plain @click="addSubsidiaryInfoRow"  type="primary">+添加档口</u-button>
        </template>
        <!-- 我要选款 -->
        <template v-if="assignType === 2">
          <u-form labelWidth="100" labelPosition="top" class="bg-fff">
            <u-form-item label="企业名称" class="u-border-bottom u-p-t-24 u-p-r-30 u-p-b-24 u-p-l-30" :style="style">
              <u-input v-model="formData.enterpriseName" :border="false"  placeholder="请输入企业名称" />
            </u-form-item>
            <u-form-item label="企业联系人" class="u-border-bottom u-p-t-24 u-p-r-30 u-p-b-24 u-p-l-30" :style="style">
              <u-input v-model="formData.corporateContactName" :border="false"  placeholder="请输入企业联系人" />
            </u-form-item>
            <u-form-item label="档口地址" class="u-border-bottom u-p-t-24 u-p-r-30 u-p-b-24 u-p-l-30" :style="style">
              <u-input :border="false"  placeholder="请输入档口地址"
                       v-model="form2.subsidiaryInfoDTOList[form2.subsidiaryInfoDTOList.length - 1].stallAddress"
              />
            </u-form-item>
          </u-form>
          <view class="u-p-t-24 u-p-r-30 u-p-b-24 u-p-l-30 u-m-b-30 u-m-t-30 bg-fff">
            <u-collapse accordion>
              <u-collapse-item v-for="(item,index) in brandInfo"  :key="index">
                <view slot="title">
                  <text class="u-page__item__title__slot-title">品牌{{ index + 1 }}</text>
                  <text @click.stop="delBrandRow(item)">删除</text>
                </view>

                <view class="u-collapse-content">
                  <u-form labelWidth="100" labelPosition="top" >
                    <u-form-item label="品牌名称" :style="style">
                      <u-input v-model="item.brandName" :border="false" placeholder="请输入品牌名称" />
                    </u-form-item>
                    <u-form-item label="品牌定位" :style="style">
                      <u-input v-model="item.brandFixedText" :border="false" placeholder="请输入品牌定位"
                               :select-open="show"
                               type="select" @click="() => { show = true; rowIndex = index}"
                               readonly/>
                    </u-form-item>
                  </u-form>
                </view>
              </u-collapse-item>
            </u-collapse>
          </view>

          <u-button plain @click="addBrandRow" type="primary">+添加品牌</u-button>
          <u-select v-model="show" mode="single-column" :list="column" @confirm="selectConfirm"></u-select>
        </template>
        <!-- 设计机构 -->
        <template v-if="assignType === 3">
          <u-form labelWidth="150" labelPosition="top">
            <u-form-item label="机构名称" class="u-border-bottom u-p-t-24 u-p-r-30 u-p-b-24 u-p-l-30" :style="style">
              <u-input v-model="formData.enterpriseName" :border="false" placeholder="请输入机构名称" />
            </u-form-item>
            <u-form-item label="机构联系人" class="u-border-bottom u-p-t-24 u-p-r-30 u-p-b-24 u-p-l-30" :style="style">
              <u-input v-model="formData.corporateContactName" :border="false" placeholder="请输入机构联系人" />
            </u-form-item>
            <u-form-item label="机构地址" class="u-border-bottom u-p-t-24 u-p-r-30 u-p-b-24 u-p-l-30" :style="style">
              <u-input v-model="formData.institutionAddress" :border="false" placeholder="请输入机构地址" />
            </u-form-item>
            <u-form-item label="合作方式(可多选)" class="u-border-bottom u-p-t-24 u-p-r-30 u-p-b-24 u-p-l-30" :style="style">
              <u-checkbox-group>
                <view class="u-tag u-size-default u-shape-circle u-mode-plain-primary"
                      :key="index"
                      v-for="(item, index) in checkbox">
                  <u-checkbox iconClass="displayNone" @change="checkChange"
                              v-model="item.checked"

                              :name="item.value"
                  >{{item.label}}</u-checkbox>
                </view>
              </u-checkbox-group>
            </u-form-item>
          </u-form>
        </template>
        <!-- 检测结构 -->
        <template v-if="assignType === 4">
          <u-form labelWidth="100" labelPosition="top">
            <u-form-item label="机构名称" class="u-border-bottom u-p-t-24 u-p-r-30 u-p-b-24 u-p-l-30" :style="style">
              <u-input v-model="formData.enterpriseName" :border="false" placeholder="请输入机构名称" />
            </u-form-item>
            <u-form-item label="机构联系人" class="u-border-bottom u-p-t-24 u-p-r-30 u-p-b-24 u-p-l-30" :style="style">
              <u-input v-model="formData.corporateContactName" :border="false" placeholder="请输入机构联系人" />
            </u-form-item>
            <u-form-item label="机构地址" class="u-border-bottom u-p-t-24 u-p-r-30 u-p-b-24 u-p-l-30" :style="style">
              <u-input v-model="formData.institutionAddress" :border="false" placeholder="请输入机构地址" />
            </u-form-item>
          </u-form>
        </template>
      </view>
      <!-- 完成 -->
      <view v-if="current === 2">
        <view class="status u-text-center">
          <view class="circle">
            <u-icon name="checkbox-mark" color="#fff" size="36"></u-icon>
          </view>
          <view class="u-m-t-40">
            <view class="status-text">
              {{
                error ? "提交失败" : "提交成功"
              }}
            </view>
            <view v-if="error" class="status-desc">请返回上一步重新提交</view>
            <view v-if="!error" class="status-desc">
              <view>确认后立刻跳转首页</view>
              <view>（{{time}}秒）后自动跳转</view>
            </view>
          </view>
        </view>
      </view>

      <!-- 删除模态框 -->
      <u-modal v-model="modal.show" :content="modal.content"  @confirm="modalConfirm" ></u-modal>
    </view>
    <!-- 底部按钮 -->
    <view class="footer" id="footer">
      <view class="footer-btn u-p-t-12 u-p-r-60 u-p-b-12 u-p-l-60">
        <u-button type="primary" @click="next" shape="circle" :disabled="assignType === -1" v-if="current === 0">下一步
        </u-button>
        <u-button type="primary" @click="submit" shape="circle" v-if="current === 1" :disabled="!canSubmit">下一步</u-button>
        <u-button type="primary" @click="back" shape="circle" v-if="current === 2 && error">返回</u-button>
      </view>
    </view>
  </view>

</template>

<script>
import UserSelect from "./components/UserSelect";
import Steps from "./components/Steps";

export default {
  name: "register",
  components: {Steps, UserSelect},
  data(){
    return{
      current: 0,
      userSelect: [
        {
          title: "我是面料供应商",
          desc: "Fabric supplier",
          imgSrc: "/static/images/index/userSelect/type_1.png",
          activeImgSrc: "/static/images/index/userSelect/type_1_active.png",
        },
        {
          title: "我要选款",
          desc: "I want to choose",
          imgSrc: "/static/images/index/userSelect/type_2.png",
          activeImgSrc: "/static/images/index/userSelect/type_2_active.png",
        },
        {
          title: "我是设计机构",
          desc: "Design agency",
          imgSrc: "/static/images/index/userSelect/type_3.png",
          activeImgSrc: "/static/images/index/userSelect/type_3_active.png",
        },
        {
          title: "我是检测机构",
          desc: "Testing institutions",
          imgSrc: "/static/images/index/userSelect/type_4.png",
          activeImgSrc: "/static/images/index/userSelect/type_4_active.png",
        }
      ],
      assignType: -1, //身份类型: 1-我是面料供应商 2-我要选款 3-我是设计机构 4-我是检测机构
      steps: [
        {
          title: '第一步',
          desc: '选择身份'
        },
        {
          title: '第二步',
          desc: '完善信息'
        },
        {
          title: '第三步',
          desc: '完成'
        }
      ],
      formData:{
        "enterpriseName": "", //企业名称
        "corporateContactName": "", //企业联系人姓名
        "institutionAddress": "" //企业/机构地址
      },
      error: true,
      time: 3,
      modal:{
        show: false,
        content: "确认删除?"
      },
      show: false,
      rowIndex: null,
      row: {},
      column: [
        {
          value: '1',
          label: '高端'
        },
        {
          value: '2',
          label: '终端'
        }
      ],
      typeDir: [
        {
          label: "承接面料建模",
          value: 1,
        },
        {
          label: "承接款式开发",
          value: 2
        },
      ],
      style: {lineHeight: 'inherit'},
      comData:{
        pcBasicsId: '',          //PC端注册的企业id
        pcUserId: '',          //PC端注册的企业id
        corporateContactId: '',  //企业联系人id
        institutionAddressId: '',//企业/机构地址id
        // "pcBasicsId": 5,
        // "pcUserId": "1422769059341709341"
      },
      form1:{
        subsidiaryInfoDTOList: [
          // {
          //   "stallAddress": "档口地址", //档口地址
          //   "stallName": "档口名称" //档口名称
          // }
        ]
      },
      form2:{
        subsidiaryInfoDTOList:[
          {stallAddress: ''}
        ],
        brandInfoDTOList: [
          // {
          //   "brandName": "品牌名称", //品牌名称
          //   "brandFixed": "品牌定位" //品牌定位
          // }
        ]
      },
      form3:{
        cooperationMethodList: [] // 合作方式
      },
      form4:{},

      footerHeight: 0,
      isInit: true,
      status:{
        isBrandOwner: 0,   // 我要选款
        isDesignAgency: 0, // 完善设计机构信息
        isFabricSupplier: 0, //完善面料供应商信息
        isTestingFacility: 0, // 完善检测机构信息
      }
    }
  },
  computed:{
    canSubmit(){

      if(this.assignType === 4){
        return this.formData.corporateContactName && this.formData.enterpriseName && this.formData.institutionAddress;
      }else if(this.assignType === 3){
        return this.formData.corporateContactName && this.formData.enterpriseName && this.formData.institutionAddress && this.form3.cooperationMethodList.length > 0;
      }else if(this.assignType === 2){
        return this.formData.corporateContactName && this.formData.enterpriseName &&  this.form2.subsidiaryInfoDTOList.length > 0 && this.form2.brandInfoDTOList.filter((item) =>{
          return item.isDeleted === false
        }).length > 0;
      }else {
        return this.formData.corporateContactName && this.formData.enterpriseName && this.form1.subsidiaryInfoDTOList.filter((item) =>{
          return item.isDeleted === false
        }).length > 0;
      }
    },
    checkbox(){
      let value = this.form3.cooperationMethodList,
       {typeDir} = this,
          res = [];
      for (let i = 0; i < typeDir.length; i++) {
        res.push({
          ...typeDir[i],
          checked: value.indexOf(typeDir[i].value) > -1
        })
      }
      return res;
    },
    subsidiaryInfo(){
      return this.form1.subsidiaryInfoDTOList.filter((item) =>{
        return item.isDeleted === false
      })
    },
    brandInfo(){
      return this.form2.brandInfoDTOList.filter((item) =>{
        return item.isDeleted === false
      })
    }
  },
  onLoad(options) {
    let {
      pcUserId,
      pcBasicsId,
      tenantUserId,
      tenantId,
      redirect
    } = options;
    this.comData = {
      ...options,
      ...{
        pcUserId: uni.getStorageSync("pcUserId") || options.pcUserId,
        pcBasicsId: uni.getStorageSync("pcBasicsId") || options.pcBasicsId,
        tenantId: uni.getStorageSync("tenantId") || options.tenantId,
      }
    };
    this.isInit = redirect !== "1";
    this.checkStatus();
  },
  mounted() {
    this.uGetRect("#footer").then(res =>{
      this.footerHeight = res.height;
    })
  },
  methods:{
    // 注册成功 跳转到首页
    goIndex(){
      this.$Router.replace({
        path: '/pages/index/index'
      })
    },
    // 获取详情 过滤状态 如果完善就跳转首页
    filterStatus(data){
      // 0-未完善 1-已完善
      let{
        isBrandOwner,   // 我要选款
        isDesignAgency, // 完善设计机构信息
        isFabricSupplier, //完善面料供应商信息
        isTestingFacility, // 完善检测机构信息
      } = data;
      // 存一份身份状态
      this.status = data;
      let { isInit, assignType} = this;
      switch (assignType){
        case 1:
          isFabricSupplier && isInit ? this.goIndex() : '';
          return ;
        case 2:
          isBrandOwner  && isInit ? this.goIndex() : '';
          return ;
        case 3:
          isDesignAgency  && isInit ? this.goIndex() : '';
          return ;
        case 4:
          isTestingFacility  && isInit ? this.goIndex() : "";
          return ;
      }
    },
    checkStatus(){
      this.$http(
          "user.checkMagStatus",
          this.comData
      ).then(res =>{
        let { code ,data} = res;
        if(code === 200){
          // 1-面料供应商, 2-品牌商, 3-设计机构, 4-检测机构
          let { identityType} = data.userLastIdentity;
          if(identityType){
            this.assignType = identityType;
            this.filterStatus(data)
          }
        }
      })
    },
    getItem(){
      this.$http(
          "user.getItemMsg",
          {
            ...this.comData,
            assignType: this.assignType
          }
      ).then(res =>{
        let { code ,data} = res;
        if(code === 200){
          let {identityType,
            supplierStudioCooperationMethodList,
            addressList,
            brandInfoList,
            basics,
            contact
          } = data;
          if(identityType !== -1){
            this.assignType = identityType;
          }

          this.form3.cooperationMethodList = supplierStudioCooperationMethodList['cooperationMethod'] || [];
          this.form1.subsidiaryInfoDTOList = addressList.length > 0 ? addressList.map((item) =>{
            return {
              ...item,
              stallAddress: item.detailedAddress,
            }
          }) : [
            {stallAddress: ''}
          ]
          this.form2.brandInfoDTOList = brandInfoList.map((item) => {
            return{
              ...item,
              brandFixedText: this.column.find(($item) => {
                return $item.value === item.brandFixed
              })?.label || ''
            }
          }) || [];
          this.form2.subsidiaryInfoDTOList = addressList.length > 0 ? addressList.map((item) =>{
            return {
              ...item,
              stallAddress: item.detailedAddress,
            }
          }): [
            {stallAddress:'' ,isDeleted: false}
          ]

          this.formData = {
            enterpriseName: basics.fullName,
            corporateContactName: contact[contact.length - 1]?.name || '',
            institutionAddress: addressList[addressList.length - 1]?.detailedAddress || '',
            corporateContactId: contact[contact.length - 1]?.id || '',  //企业联系人id
            institutionAddressId: addressList[addressList.length - 1]?.id || '',//企业/机构地址id
          }
          if(this.isInit){
            this.next();
          }
          // this.comData =
        }
      })
    },
    uGetRect(selector, all) {
      return new Promise((resolve) => {
        uni.createSelectorQuery()
            .in(this)[all ? 'selectAll' : 'select'](selector)
            .boundingClientRect((rect) => {
              if (all && Array.isArray(rect) && rect.length) {
                resolve(rect)
              }
              if (!all && rect) {
                resolve(rect)
              }
            })
            .exec()
      })
    },
    userSelectCallback(type){
      this.assignType = type;
      let {
        pcUserId,
        pcBasicsId
      } = this.comData;
      if(pcUserId && pcBasicsId){
        this.getItem();
      }
    },
    // 重新选择时 核对当前选中状态
    checkStatusByType(assignType){
      let{
        isBrandOwner,   // 我要选款
        isDesignAgency, // 完善设计机构信息
        isFabricSupplier, //完善面料供应商信息
        isTestingFacility, // 完善检测机构信息
      } = this.status;
      switch (assignType){
        case 1:
          isFabricSupplier ? this.goIndex() : '';
          return ;
        case 2:
          isBrandOwner   ? this.goIndex() : '';
          return ;
        case 3:
          isDesignAgency ? this.goIndex() : '';
          return ;
        case 4:
          isTestingFacility ? this.goIndex() : "";
          return ;
      }
    },
    next() {
      this.checkStatusByType(this.assignType);
      this.current++;
    },
    back() {
      this.current--;
      this.time = 3;
    },
    success() {
      let timer = setInterval(() => {
        this.time--;
        if (this.time === 0) {
          clearInterval(timer);
          this.$Router.replace({
            path: '/pages/index/index'
          })
        }
      }, 1000);
    },
    filterData(type){

      switch (type){
        case 1:
          return this.form1;
        case 2:
          return this.form2
        case 3:
          return this.form3
        case 4:
          return this.form4
      }
    },
    getData(){
      return {
        ...this.comData,
        ...this.formData,
        assignType: this.assignType,
        ...this.filterData(this.assignType),
      }
    },
    submit() {
      // return;
      this.$http(
          "user.register",
          this.getData()
      ).then(res =>{
         let { code ,data} = res;
         this.next();
         if(code === 200){
           uni.setStorageSync("identityType", this.assignType);
           this.error = false;
           this.createToken(data,()=>{
             this.success();
           })
         }else{
           this.error = true;
         }
      })
    },
    createToken(data,callback){
      this.$http("auth.createTokenByApp" ,data).then(res =>{
        let {
          code, data
        } = res;
        if(code === 200){
          uni.setStorageSync('token', data.accessToken);
          uni.setStorageSync('pcUserId', data.userId);
          uni.setStorageSync('pcBasicsId', data.enterpriseId);
          callback();
        }
      })
    },
    defaultSubsidiaryInfoRow() {
      return {
        "stallAddress": "", //品牌名称
        "stallName": "", //品牌定位
        "isDeleted": false
      }
    },
    addSubsidiaryInfoRow() {
      this.form1.subsidiaryInfoDTOList.push(this.defaultSubsidiaryInfoRow())
    },
    delSubsidiaryInfoRow(item,index) {
      this.row = item;
      this.rowIndex = index;
      this.modal.show = true;
    },
    defaultBrandInfoRow() {
      return {
        "brandName": "", //品牌名称
        "brandFixed": "", //品牌定位
        "brandFixedText": "", //品牌定位站位文本
        "isDeleted": false
      }
    },
    addBrandRow() {
      this.form2.brandInfoDTOList.push(this.defaultBrandInfoRow())
    },
    delBrandRow(item,index) {
      this.row = item;
      this.rowIndex = index;
      this.modal.show = true;
    },
    selectConfirm(e,index){
      let item = e[0];
      if(this.assignType === 1){

      }else{
        this.$set(
            this.form2.brandInfoDTOList,
            this.rowIndex,
            {
              ...this.form2.brandInfoDTOList[this.rowIndex],
              brandFixedText: item.label,
              brandFixed: item.value
            },
        )
      }

    },
    modalConfirm(){
      if(this.assignType === 2){
        let {row} = this, data = this.form2.brandInfoDTOList;
        if(row.id){
          let index = data.findIndex((item) =>{
            return item.id === row.id
          });
          if(index > -1){
            this.$set(data,index,{
              ...this.row,
              isDeleted: true
            })
          }
        }else{
          data.splice(
              data.findIndex((item) =>{
                return item === row;
              }),
              1);
        }
      }else{
        let {row} = this, data = this.form1.subsidiaryInfoDTOList;
        if(row.id){
          let index = data.findIndex((item) =>{
            return item.id === row.id
          });
          if(index > -1){
            this.$set(this.form1.subsidiaryInfoDTOList,index,{
              ...this.row,
              isDeleted: true
            })
          }
        }else{
          data.splice(
              data.findIndex((item) =>{
                return item === row;
              }),
              1);
        }
      }
    },
    checkChange(e){
      let { name, value} = e;

      if(value){
        this.form3.cooperationMethodList.push(name)
      }else{
        let index = this.form3.cooperationMethodList.findIndex((item) => {
          return item === name
        });
        this.form3.cooperationMethodList.splice(index,1);
      }
    }
  }
}
</script>

<style scoped lang="scss">
.circle {
  border-radius: 50%;
  width: 96rpx;
  height: 96rpx;
  background-color: rgb(60, 156, 255);
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
}
.bg-fff{
  background-color: #fff;
}
.body{
  background: #fafafa;
  position: absolute;
  width: 100%;
  height: auto;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  overflow-y: auto;
}
.displayNone{
  display: none;
}

.status {
  padding-top: 96rpx;
  height: 500rpx;
  background: #fff;
  .status-text {
    font-size: 36rpx;
    margin-bottom: 16rpx;
  }

  .status-desc {
    color: #999999;
    font-size: 26rpx;
    line-height: 36rpx;
  }
}


.footer {
  position: fixed;
  width: 100%;
  bottom: 0;

  z-index: 998;
  background: #fff;

  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);

  .footer-btn {
    // padding: 12rpx 60rpx;
  }
}
</style>
