<!-- 完善信息 -->
<template>
  <view>
    <view class="body" :style="{ bottom: footerHeight + 'px'}">
      <!-- 完善信息 -->
      <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>
          <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">
            <view v-for="(item,index) in subsidiaryInfo"  :key="index">
              <view class="u-flex">
                <view class="u-flex-1">
                  <view class="title u-m-r-22">
                    <view class="line"></view>
                    档口{{ index + 1 }}
                  </view>
                  <text class="button--delete" @click.stop="delBrandRow(item)">删除</text>
                </view>
                <view @click="brandCollapseChange(index)">
                  {{
                    brandActive === index ? "收起":"展开"
                  }}
                </view>
              </view>
              <view class="collapse-body" :style="[{
                  height: brandActive === index ? 'auto' : '0'
                }]">
                <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>

            </view>
          </view>
          <view class="button-plain" @click="addSubsidiaryInfoRow">+添加档口</view>
        </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">
            <view v-for="(item,index) in brandInfo"  :key="index">
              <view class="u-flex">
                <view class="u-flex-1">
                  <view class="title u-m-r-22">
                    <view class="line"></view>
                    品牌{{ index + 1 }}
                  </view>
                  <text class="button--delete" @click.stop.self="delBrandRow(item)">删除</text>
                </view>
                <view @click="InfoCollapseChange(index)">
                  {{
                    brandActive === index ? "收起":"展开"
                  }}
                </view>
              </view>
              <view class="collapse-body" :style="[{
                  height: brandActive === index ? 'auto' : '0'
                }]">
                <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>

            </view>
          </view>

          <view class="button-plain" @click="addBrandRow">+添加品牌</view>
          <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>
    <!-- 底部按钮 -->
    <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">
<!--        :class="[!canSubmit ? 'button&#45;&#45;submit&#45;&#45;disabled' : '' ]"-->
        <u-button type="primary" @click="submit" shape="circle"
                  v-if="current === 1"  class="button--submit"
                  :custom-style=" assignType === -1 ? {background: '#b5b5b5 !important'} : {background: '#333 !important'}"

                  :disabled="!canSubmit">下一步</u-button>
      </view>
    </view>

    <u-toast ref="uToast" />
  </view>

</template>

<script>
import UserSelect from "./components/UserSelect";
import Steps from "./components/Steps";
import dom from '@/mixins/dom'
import goIndex from "./mixins/goIndex";
export default {
  name: "register",
  components: {Steps, UserSelect},
  mixins: [dom,goIndex],
  data(){
    return{
      current: 1,
      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,

      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, // 完善检测机构信息
      },
      brandActive: 0,
      infoActive: 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.brandInfoDTOList.length === 0 ||
            this.validateBrandItem(
                this.form2.brandInfoDTOList.filter((item) =>{
                  return item.isDeleted === false
                })
            )
        )
      }else {
        return (
            this.formData.corporateContactName && this.formData.enterpriseName && (
                this.form1.subsidiaryInfoDTOList.length === 0 ||
                this.validateInfoItem(
                    this.form1.subsidiaryInfoDTOList.filter((item) =>{
                      return item.isDeleted === false
                    })
                )
            )
        )
      }
    },
    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) {
    this.comData = {
      ...options,
      ...{
        pcUserId: uni.getStorageSync("pcUserId") || options.pcUserId,
        pcBasicsId: uni.getStorageSync("pcBasicsId") || options.pcBasicsId,
        tenantId: uni.getStorageSync("tenantId") || options.tenantId,
      }
    };
    this.assignType = Number(options.type)
    if(this.comData.pcBasicsId && this.comData.pcUserId){
      this.getItem();
    }
  },
  mounted() {
    this.uGetRect("#footer").then(res =>{
      this.footerHeight = res.height;
    })
  },
  methods:{
    validateInfoItem(data){
      let res = true;
      for (let i = 0; i < data.length; i++) {
        let item = data[i];
        if(item.stallAddress && item.stallName){

        }else{
          res = false
        }
      }
      return res;
    },
    validateBrandItem(data){
      let res = true;
      for (let i = 0; i < data.length; i++) {
        let item = data[i];
        if(item.brandName && item.brandFixed){

        }else{
          res = false
        }
      }
      return res;
    },
    brandCollapseChange(index){
      this.brandActive = this.brandActive === index ? null: index;
    },
    InfoCollapseChange(index){
      this.infoActive = this.infoActive === index ? null: index;
    },

    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 && identityType){
            this.assignType = identityType;
          }

          this.form3.cooperationMethodList = supplierStudioCooperationMethodList['cooperationMethod'] || [];
          this.form1.subsidiaryInfoDTOList = addressList.length > 0 ? addressList.map((item) =>{
            return {
              ...item,
              stallAddress: item.detailedAddress
            }
          }) : [
            {stallAddress: '',isDeleted: false}
          ]
          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
          }
        }
      })
    },
    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 ;
      }
    },
    goEndPage(isSuccess){
      this.$Router.push({
        path: '/pages/user/register/success',
        query:{
          status: isSuccess ? 'success':'error'
        }
      })
    },
    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() {
      this.$http(
          "user.register",
          this.getData()
      ).then(res =>{
        let { code ,data,msg} = res;
        if(code === 200){
          uni.setStorageSync("identityType", this.assignType);
          this.createToken(data,()=>{
            this.$Router.back()
          })
        }else{
          uni.showToast({
            title: msg
          })
          // this.error = true;
          //this.goEndPage(false)
        }
      })
    },
    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);
          uni.setStorageSync('userInfo', data);
          callback();
        }
      })
    },
    defaultSubsidiaryInfoRow() {
      return {
        "stallAddress": "", //品牌名称
        "stallName": "", //品牌定位
        "isDeleted": false
      }
    },
    addSubsidiaryInfoRow() {
      let list = this.form1.subsidiaryInfoDTOList.filter((item) =>{
        return item.isDeleted === false
      });
      if(list.length < 10){
        this.form1.subsidiaryInfoDTOList.push(this.defaultSubsidiaryInfoRow())
      }else{
        this.$refs.uToast.show({
          title: '最多添加10条',
        })
      }
    },
    delSubsidiaryInfoRow(item,index) {
      this.row = item;
      this.rowIndex = index;
      this.delModal();
      // this.modal.show = true;
    },
    defaultBrandInfoRow() {
      return {
        "brandName": "", //品牌名称
        "brandFixed": "", //品牌定位
        "brandFixedText": "", //品牌定位站位文本
        "isDeleted": false
      }
    },
    addBrandRow() {
      let list = this.form2.brandInfoDTOList.filter((item) =>{
        return item.isDeleted === false
      });
      if(list.length < 10){
        this.form2.brandInfoDTOList.push(this.defaultBrandInfoRow())
      }else{
        this.$refs.uToast.show({
          title: '最多添加10条',
        })
      }

    },
    delModal(){
      uni.showModal({
        title: '提示',
        content: '是否删除数据',
        success: (res) =>{
          if (res.confirm) {
            this.modalConfirm();
            // console.log('用户点击确定');
          } else if (res.cancel) {
            // console.log('用户点击取消');
          }
        }
      });
    },
    delBrandRow(item,index) {
      this.row = item;
      this.rowIndex = index;
      this.delModal();
      // 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">
@import './css/index';
</style>
