<template>
  <div class="page-content">
    <div class="add-cusUser-detail detailClass">
      <van-form @submit="onSubmit" validate-trigger="onSubmit">
        <van-field name="cusName" v-model="popObj.cusName" label="机构名" placeholder="请输入机构名" :required="true"
          :rules="[{ required: true, message: '请填写机构名' }]" />
        <van-field clickable name="cusLevelName" v-model="popObj.cusLevelName" label="机构评级" placeholder="点击选择机构评级"
          @click="popObj.handleShowPop1('cusLevel', '机构评级')" readonly />
        <van-popup v-model:show="popObj.showPop1" position="bottom">
          <van-picker show-toolbar :title="popObj.popTitle" :columns="popObj[`${popObj.type}List`]"
            @confirm="popObj.onConfirm1($event)" @cancel="popObj.showPop1 = false" v-model="popObj.value1" />
        </van-popup>
        <van-field clickable name="cusUserName" v-model="popObj.cusUserName" label="核心联系人" placeholder="点击选择机构"
          @click="popObj.handleShowPop2('cusUser', '核心联系人')" readonly />
        <van-popup v-model:show="popObj.showPop2" position="bottom">
          <div class="d-flex align-items-center">
            <van-field v-model="popObj.searchValue" :placeholder="'请输入' + popObj.popTitle"
              @input="popObj.onSearchInput" />
            <van-button block type="success" size="small" native-type="button" @click="toAddCusUser"
              style="width: 60px; margin: 12px 16px 0 0">
              新增
            </van-button>
          </div>
          <van-picker show-toolbar :title="popObj.popTitle" :columns="popObj.showPop2List"
            @confirm="popObj.onConfirm2($event)" @cancel="popObj.showPop2 = false" />
        </van-popup>
        <van-field clickable name="companyTypeName" v-model="popObj.companyTypeName" label="机构类型" placeholder="点击选择机构类型"
          @click="popObj.handleShowPop1('companyType', '机构类型')" readonly />
        <van-field clickable name="cityName" v-model="popObj.cityName" label="城市" placeholder="点击选择城市"
          @click="popObj.handleShowPop1('city', '城市')" readonly />
        <van-field name="address" v-model="popObj.address" label="地址" placeholder="请输入地址" />
        <van-field name="radio" label="是否开户">
          <template #input>
            <van-radio-group v-model="popObj.accountStatus" direction="horizontal">
              <van-radio name="0">否</van-radio>
              <van-radio name="1">是</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field v-show="popObj.accountStatus === '1'" clickable name="accountTime" v-model="popObj.accountTime"
          label="开户时间" placeholder="点击选择日期" @click="popObj.handleShowPop4('accountTime', '开户时间')" readonly />
        <van-popup v-model:show="popObj.showPop4" position="bottom">
          <van-date-picker v-model="popObj.value4" :title="popObj.popTitle" @confirm="popObj.onConfirm4($event)"
            @cancel="popObj.showPop4 = false" />
        </van-popup>
        <van-field v-show="popObj.accountStatus === '1'" clickable name="accountTypeNames"
          v-model="popObj.accountTypeNames" label="开户类型" placeholder="点击选择开户类型"
          @click="popObj.handleShowPop3('accountType', '开户类型')" readonly />
        <van-popup v-model:show="popObj.showPop3" position="bottom">
          <div class="p-16 box-popup">
            <van-row class="mb-16">
              <van-col span="8">
                <van-button class="van-picker__cancel" native-type="button"
                  @click="popObj.showPop3 = false">取消</van-button>
              </van-col>
              <van-col span="8" class="text-center">
                <span class="sub-title f-b">请选择{{ popObj.popTitle }}</span>
              </van-col>
              <van-col span="8" class="text-end">
                <van-button class="van-picker__confirm" native-type="button" @click="popObj.onConfirm3">确认</van-button>
              </van-col>
            </van-row>
            <van-checkbox-group v-model="popObj.value3" direction="horizontal">
              <van-checkbox v-for="(item, index) in popObj[`${popObj.type}List`]" :key="index" :name="item.value"
                shape="square">
                {{ item.text }}
              </van-checkbox>
            </van-checkbox-group>
          </div>
        </van-popup>
        <van-field v-show="popObj.accountStatus === '1'" name="radio" label="是否交易">
          <template #input>
            <van-radio-group v-model="popObj.isMoney" direction="horizontal">
              <van-radio name="0">否</van-radio>
              <van-radio name="1">是</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field v-show="popObj.accountStatus === '1' && popObj.isMoney === '1'" name="tradeMoney"
          v-model="popObj.tradeMoney" label="交易总金额" placeholder="请输入交易总金额" />
        <van-field v-show="popObj.accountStatus === '1' && popObj.isMoney === '1'" clickable name="capitalScaleName"
          v-model="popObj.capitalScaleName" label="资金规模(亿)" placeholder="点击选择资金规模"
          @click="popObj.handleShowPop1('capitalScale', '资金规模')" readonly />
        <van-field v-show="popObj.accountStatus === '1' && popObj.isMoney === '1'" name="capitalScaleValue"
          v-model="popObj.capitalScaleValue" label="资金规模(亿)" placeholder="请输入资金规模" @blur="popObj.setAccountStatus" />
        <van-field name="fundNum" v-model="popObj.fundNum" label="基金数量" placeholder="请输入基金数量" />
        <van-field name="investOverseasPer" v-model="popObj.investOverseasPer" label="海外投资占比" placeholder="请输入海外投资占比" />
        <van-field name="investResearchNum" v-model="popObj.investResearchNum" label="投研人数" placeholder="请输入投研人数" />
        <van-field clickable name="investChannelName" v-model="popObj.investChannelName" label="投资渠道"
          placeholder="点击选择投资渠道" @click="popObj.handleShowPop1('investChannel', '投资渠道')" readonly />
        <van-field name="website" v-model="popObj.website" label="公司网站" placeholder="请输入公司网站" />
        <van-field clickable name="companyCreateTime" v-model="popObj.companyCreateTime" label="开户时间"
          placeholder="点击选择公司创建时间" @click="popObj.handleShowPop4('companyCreateTime', '公司创建时间')" readonly />
        <van-field name="introduction" v-model="popObj.introduction" label="公司简介" rows="3" type="textarea" autosize />
        <van-field clickable name="saleUserNames" v-model="popObj.saleUserNames" label="负责人" placeholder="点击选择负责人"
          @click="popObj.handleShowPop3('saleUser', '负责人')" readonly />
        <div class="m-16 d-flex justify-content-center">
          <van-button round block type="primary" size="small" native-type="submit"
            :disabled="submitFlag">提交</van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import moment from 'moment'
import emitter from '@/utils/mitt'
import { sysDicListByType, sysUserGetSaleAndManagerList, cusUserLookUp, cusInfoSave } from '@/utils/api'
let submitFlag = ref(false)

import { debounceThrottle } from '@/mixins/debounce-throttle'
const { throttle } = debounceThrottle()
import { type CusObj } from '@/utils/types'
const popObj: CusObj = reactive({
  showPop1: false,
  showPop2: false,
  showPop3: false,
  showPop4: false,
  popTitle: '',
  type: '',
  value1: [],
  value3: [],
  value4: [],
  cusName: '',
  cusLevelName: '',
  selectcusLevel: '',
  cusLevelList: [],
  cusUserName: '',
  selectcusUser: '',
  searchValue: '',
  showPop2List: [],
  companyTypeName: '',
  selectcompanyType: '',
  companyTypeList: [],
  cityName: '',
  selectcity: '',
  cityList: [],
  address: '',
  accountStatus: '1',
  accountTime: '',
  selectaccountTime: [],
  accountTypeNames: '',
  selectaccountTypeIds: [],
  accountTypeList: [],
  isMoney: '0',
  tradeMoney: '',
  capitalScaleName: '',
  selectcapitalScale: '',
  capitalScaleList: [],
  capitalScaleValue: '',
  fundNum: '',
  investOverseasPer: '',
  investResearchNum: '',
  investChannelName: '',
  selectinvestChannel: '',
  investChannelList: [],
  website: '',
  companyCreateTime: '',
  selectcompanyCreateTime: [],
  introduction: '',
  saleUserNames: '',
  selectsaleUserIds: [],
  saleUserList: [],
  handleShowPop1: (val: string, title: string) => {
    popObj.showPop1 = true
    popObj.popTitle = title
    popObj.type = val
    popObj.value1 = [popObj[`select${val}`]]
  },
  handleShowPop2: (val: string, title: string) => {
    popObj.showPop2 = true
    popObj.popTitle = title
    popObj.type = val
    popObj.searchValue = popObj[`${val}Name`]
    popObj.showPop2List = popObj[`select${val}`] ? [{ text: popObj[`${val}Name`], value: popObj[`select${val}`] }] : []
  },
  handleShowPop3: (val: string, title: string) => {
    popObj.showPop3 = true
    popObj.popTitle = title
    popObj.type = val
    popObj.value3 = popObj[`select${val}Ids`]
  },
  handleShowPop4: (val: string, title: string) => {
    popObj.popTitle = title
    popObj.type = val
    if (popObj[`select${val}`].length === 0) {
      let nowDay = moment().format('YYYY-MM-DD HH:mm:ss')
      popObj.value4 = nowDay.slice(0, 10).split('-')
    } else {
      popObj.value4 = popObj[`select${val}`]
    }
    popObj.showPop4 = true
  },
  onConfirm1: ({ selectedOptions }) => {
    if (selectedOptions) {
      popObj[`select${popObj.type}`] = selectedOptions[0].value
      popObj[`${popObj.type}Name`] = selectedOptions[0].text
      if (popObj.type === 'capitalScale') {
        if (popObj.capitalScale === '1') {
          if (Number(popObj.capitalScaleValue) > 10) {
            popObj.capitalScaleValue = ''
          }
        } else if (popObj.capitalScale === '2') {
          if (Number(popObj.capitalScaleValue) > 100 || Number(popObj.capitalScale) < 10) {
            popObj.capitalScaleValue = ''
          }
        } else if (popObj.capitalScale === '3') {
          if (Number(popObj.capitalScaleValue) < 100) {
            popObj.capitalScaleValue = ''
          }
        }
      }
    }
    popObj.showPop1 = false
  },
  onSearchInput: throttle(
    async () => {
      if (popObj.searchValue) {
        const { data } = await cusUserLookUp({ cusUserName: popObj.searchValue })
        popObj.showPop2List = data.map((ele: any) => {
          ele.text = `${ele.cusUserName}${ele.positionName ? '【' + ele.positionName + '】' : ''}`
          ele.value = ele.cusUserId
          return ele
        })
      } else {
        popObj.showPop2List = []
      }
    },
    500
  ),
  onConfirm2: ({ selectedOptions }) => {
    if (selectedOptions && selectedOptions[0]) {
      popObj[`select${popObj.type}`] = selectedOptions[0].value
      popObj[`${popObj.type}Name`] = selectedOptions[0].text
      popObj.showPop2 = false
    } else {
      showToast(`请选择${popObj.popTitle}后，再确认`)
    }
  },
  onConfirm3: () => {
    popObj[`select${popObj.type}Ids`] = popObj.value3
    const sameList = popObj[`${popObj.type}List`].filter((ele: any) => popObj.value3.some((res: any) => {
      return ele.value === res
    }))
    let names = ''
    sameList.forEach((ele: any) => {
      names += `${ele.text},`
    })
    if (names) {
      names = names.substring(0, names.length - 1)
    }
    popObj[`${popObj.type}Names`] = names
    popObj.showPop3 = false
  },
  onConfirm4: ({ selectedValues }) => {
    if (selectedValues) {
      popObj[popObj.type] = `${selectedValues[0]}-${selectedValues[1]}-${selectedValues[2]}`
      popObj[`select${popObj.type}`] = selectedValues
    }
    popObj.showPop4 = false
  },
  setAccountStatus: () => {
    if (Number(popObj.capitalScaleValue) >= 0 && Number(popObj.capitalScaleValue) < 10) {
      popObj.selectcapitalScale = '1'
    } else if (Number(popObj.capitalScaleValue) >= 10 && Number(popObj.capitalScaleValue) < 100) {
      popObj.selectcapitalScale = '2'
    } else if (Number(popObj.capitalScaleValue) >= 100) {
      popObj.selectcapitalScale = '3'
    } else {
      popObj.selectcapitalScale = ''
    }
    let index = popObj.capitalScaleList.findIndex((ele: any) => {
      return ele.dicKey === popObj.selectcapitalScale
    })
    if (index > -1) {
      popObj.capitalScaleName = popObj.capitalScaleList[index].dicValue
    } else {
      popObj.capitalScaleName = ''
    }
  }
})
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
import saveCusInfoStore from '@/stores/saveCusInfo'
const saveCusInfo: any = saveCusInfoStore()
import saveInfoStore from '@/stores/saveInfo'
const saveInfo: any = saveInfoStore()
let linkId: any = ''
const getSelectList = async () => {
  linkId = route.query.linkId
  emitter.emit('showLoading', '')
  const data1 = await sysDicListByType({ dicType: 'cus_level' })
  popObj.cusLevelList = data1.data.map((ele: any) => {
    ele.text = ele.dicValue
    ele.value = ele.dicKey
    return ele
  })
  const data2 = await sysDicListByType({ dicType: 'sale_company_type' })
  popObj.companyTypeList = data2.data.map((ele: any) => {
    ele.text = ele.dicValue
    ele.value = ele.dicKey
    return ele
  })
  const data3 = await sysDicListByType({ dicType: 'cus_city' })
  popObj.cityList = data3.data.map((ele: any) => {
    ele.text = ele.dicValue
    ele.value = ele.dicKey
    return ele
  })
  const data4 = await sysDicListByType({ dicType: 'account_type' })
  popObj.accountTypeList = data4.data.map((ele: any) => {
    ele.text = ele.dicValue
    ele.value = ele.dicKey
    return ele
  })
  const data5 = await sysDicListByType({ dicType: 'invest_channel' })
  popObj.investChannelList = data5.data.map((ele: any) => {
    ele.text = ele.dicValue
    ele.value = ele.dicKey
    return ele
  })
  const data6 = await sysUserGetSaleAndManagerList()
  popObj.saleUserList = data6.data.map((ele: any) => {
    ele.value = ele.userId
    ele.text = ele.userName
    return ele
  })
  const data7 = await sysDicListByType({ dicType: 'sale_capital_scale' })
  popObj.capitalScaleList = data7.data.map((ele: any) => {
    ele.text = ele.dicValue
    ele.value = ele.dicKey
    return ele
  })
  for (let i in saveCusInfo) {
    if (Object.prototype.hasOwnProperty.call(popObj, i)) {
      popObj[i] = saveCusInfo[i]
    }
  }
  if (saveInfo.type === 'cusUser') {
    popObj.cusUserName = `${saveInfo.name}${saveInfo.positionName ? '【' + saveInfo.positionName + '】' : ''}`
    popObj.selectcusUser = saveInfo.id
    saveInfo.$reset()
  }
  emitter.emit('hiddenLoading', '')
}

const handleKeyUp = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    event.preventDefault()
  }
}

onMounted(() => {
  window.addEventListener('keyup', handleKeyUp)
})

onUnmounted(() => {
  window.removeEventListener('keyup', handleKeyUp)
})

const toAddCusUser = () => {
  for (let i in saveCusInfo) {
    if (Object.prototype.hasOwnProperty.call(popObj, i)) {
      saveCusInfo[i] = popObj[i]
    }
  }
  if (linkId) {
    router.push({ name: 'add-cusUser', query: { linkId: linkId, from: 'cus' } })
  } else {
    router.push({ name: 'add-cusUser', query: { linkId: linkId, from: 'cus' } })
  }
}

const onSubmit = async () => {
  submitFlag.value = true
  const res: any = {
    cusName: popObj.cusName,
    cusLevel: popObj.selectcusLevel || 'E',
    cusUserId: popObj.selectcusUser || null,
    cusUserIdList: popObj.selectcusUser ? [popObj.selectcusUser] : [],
    companyType: popObj.selectcompanyType || null,
    city: popObj.selectcity || null,
    address: popObj.address,
    accountStatus: popObj.accountStatus,
    accountTypeList: popObj.accountStatus === '1' && popObj.selectaccountTypeIds.length > 0 ?
      popObj.selectaccountTypeIds : null,
    accountTime: popObj.accountStatus === '1' && popObj.accountTime ?
      popObj.accountTime : null,
    tradeMoney: popObj.accountStatus === '1' && (popObj.tradeMoney === '1' || popObj.tradeMoney === '0') ?
      popObj.tradeMoney : null,
    capitalScaleValue: popObj.capitalScaleValue || null,
    capitalScale: popObj.selectcapitalScale || null,
    fundNum: popObj.fundNum || null,
    investOverseasPer: popObj.investOverseasPer || null,
    investResearchNum: popObj.investResearchNum || null,
    investChannel: popObj.selectinvestChannel || null,
    website: popObj.website || null,
    companyCreateTime: popObj.companyCreateTime || null,
    introduction: popObj.introduction || null,
    saleUserIdList: popObj.selectsaleUserIds || null
  }
  const data: any = await cusInfoSave(res)
  if (data.code === 0) {
    showToast('提交成功')
    saveInfo.id = data.data.cusId
    saveInfo.name = data.data.cusName
    saveInfo.type = 'cus'
    saveCusInfo.$reset()
    router.go(-1)
  } else {
    showToast(data.msg)
    submitFlag.value = false
  }
}

getSelectList()
</script>

<style lang='scss' scoped>
.add-cusUser-detail {
  height: 100vh;
  overflow-y: auto;
}

.detailClass {
  .van-cell {
    margin: 12px 16px 0;
    width: calc(100vw - 32px);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);

    @media screen and (min-width: 678px) {
      width: 646px;
    }
  }
}

:deep(.van-field__control) {
  color: #000 !important;
}

:deep(.van-checkbox) {
  margin-right: 0 !important;
  width: 50%;
  margin-bottom: 5px;
}
</style>
