<template>
  <div class="page-content">
    <div class="add-cus-detail detailClass">
      <van-form @submit="onSubmit" validate-trigger="onSubmit">
        <van-field name="cusUserName" v-model="popObj.cusUserName" label="联系人" placeholder="请输入联系人" :required="true"
          :rules="[{ required: true, message: '请填写联系人' }]" />
        <van-field clickable name="positionName" v-model="popObj.positionName" label="职位" placeholder="点击选择职位"
          @click="popObj.handleShowPop1('position', '职位')" readonly :required="true"
          :rules="[{ required: true, message: '请填写职位' }]" />
        <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="saleUserNames" v-model="popObj.saleUserNames" label="跟进人" placeholder="点击选择跟进人"
          @click="popObj.handleShowPop3('saleUser', '跟进人')" 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 name="phone" v-model="popObj.phone" label="座机号" placeholder="请输入座机号" />
        <van-field name="mobile" v-model="popObj.mobile" label="手机号" placeholder="请输入手机号" />
        <van-field name="email" v-model="popObj.email" label="邮箱" placeholder="请输入邮箱" />
        <van-field name="wxName" v-model="popObj.wxName" label="微信名" placeholder="请输入微信名" />
        <van-field name="address" v-model="popObj.address" label="地址" placeholder="请输入地址" />
        <van-field name="preference" v-model="popObj.preference" label="擅长" placeholder="请输入擅长" />
        <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 emitter from '@/utils/mitt'
import { cusUserCusPositionList, sysUserGetSaleAndManagerList, cusUserSave } from '@/utils/api'
let submitFlag = ref(false)

import { type CusUserObj } from '@/utils/types'
const popObj: CusUserObj = reactive({
  showPop1: false,
  showPop3: false,
  popTitle: '',
  type: '',
  value1: [],
  value3: [],
  cusUserName: '',
  positionName: '',
  selectposition: '',
  positionList: [],
  saleUserNames: '',
  selectsaleUserIds: [],
  saleUserList: [],
  selectcusUser: '',
  phone: '',
  mobile: '',
  email: '',
  wxName: '',
  address: '',
  preference: '',
  handleShowPop1: (val: string, title: string) => {
    popObj.showPop1 = true
    popObj.popTitle = title
    popObj.type = val
    popObj.value1 = [popObj[`select${val}`]]
  },
  handleShowPop3: (val: string, title: string) => {
    popObj.showPop3 = true
    popObj.popTitle = title
    popObj.type = val
    popObj.value3 = popObj[`select${val}Ids`]
  },
  onConfirm1: ({ selectedOptions }) => {
    if (selectedOptions) {
      popObj[`select${popObj.type}`] = selectedOptions[0].value
      popObj[`${popObj.type}Name`] = selectedOptions[0].text
    }
    popObj.showPop1 = false
  },
  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
  }
})

import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
let cusId: any = ''
let linkId: any = ''
let from: any = ''
const getSelectList = async () => {
  if (route.query && route.query.from) {
    cusId = route.query && route.query.cusId ? route.query.cusId : ''
    linkId = route.query && route.query.linkId ? route.query.linkId : ''
    from = route.query.from
    emitter.emit('showLoading', '')
    const data1 = await cusUserCusPositionList()
    popObj.positionList = data1.data.map((ele: any) => {
      ele.text = ele.dicValue
      ele.value = ele.dicKey
      return ele
    })
    const data2 = await sysUserGetSaleAndManagerList()
    popObj.saleUserList = data2.data.map((ele: any) => {
      ele.value = ele.userId
      ele.text = ele.userName
      return ele
    })
    emitter.emit('hiddenLoading', '')
  } else {
    router.push({ name: '404' })
  }
}

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

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

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

import saveInfoStore from '@/stores/saveInfo'
const saveInfo: any = saveInfoStore()
const onSubmit = async () => {
  submitFlag.value = true
  const res: any = {
    cusUserName: popObj.cusUserName,
    positionId: popObj.selectposition || null,
    saleUserIdList: popObj.selectsaleUserIds || null,
    phone: popObj.phone || null,
    mobile: popObj.mobile || null,
    email: popObj.email || null,
    wxName: popObj.wxName || null,
    address: popObj.address || null,
    preference: popObj.preference || null
  }
  if (cusId) {
    res.cusId = cusId
  }
  const data: any = await cusUserSave(res)
  if (data.code === 0) {
    showToast('提交成功')
    saveInfo.id = data.data.cusUserId
    saveInfo.name = data.data.cusUserName
    saveInfo.positionName = data.data.positionName
    saveInfo.type = 'cusUser'
    router.go(-1)
  } else {
    submitFlag.value = false
  }
}

getSelectList()
</script>

<style lang='scss' scoped>
.add-cus-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>
