<template>
  <div class="page-content">
    <div class="communicate-detail" :class="disabledFlag ? 'detailClass2' : 'detailClass1'">
      <van-form @submit="onSubmit" validate-trigger="onSubmit">
        <!-- <van-field clickable name="linkTypeName" v-model="popObj.linkTypeName" label="沟通项目"
          :placeholder="disabledFlag ? '' : '点击选择沟通项目'" @click="popObj.handleShowPop1('linkType', '沟通项目')"
          :required="!disabledFlag" :rules="[{ required: true, message: '请选择沟通项目' }]" readonly
          :disabled="disabledFlag" />
        <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="linkTypeName" v-model="popObj.linkTypeName" label="沟通项目"
          :placeholder="disabledFlag ? '' : '点击选择沟通项目'" @click="popObj.handleShowPop1('linkType', '沟通项目')"
          :required="!disabledFlag" :rules="[{ required: true, message: '请选择沟通项目' }]" readonly
          :disabled="disabledFlag" />
        <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="sysDay" v-model="popObj.sysDay" label="沟通日期"
          :placeholder="disabledFlag ? '' : '点击选择日期'" @click="popObj.handleShowPop4('sysDay', '选择日期', 4)"
          :required="!disabledFlag" :rules="[{ required: true, message: '请选择沟通日期' }]" readonly :disabled="disabledFlag"
          v-show="popObj.dicNote2 === '2'" />
        <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 clickable name="sysTime" v-model="popObj.sysTime" label="沟通时间"
          :placeholder="disabledFlag ? '' : '点击选择时间'" @click="popObj.handleShowPop4('sysTime', '选择时间', 5)"
          :required="!disabledFlag" :rules="[{ required: true, message: '请选择沟通时间' }]" readonly :disabled="disabledFlag"
          v-show="popObj.dicNote2 === '2'" />
        <van-popup v-model:show="popObj.showPop5" position="bottom">
          <van-time-picker v-model="popObj.value5" :title="popObj.popTitle" @confirm="popObj.onConfirm4($event)"
            @cancel="popObj.showPop5 = false" />
        </van-popup>
        <van-field clickable name="cusName" v-model="popObj.cusName" label="机构"
          :placeholder="disabledFlag ? '' : '点击选择机构'" @click="popObj.handleShowPop2('cus', '机构')"
          :required="!disabledFlag" :rules="[{ required: true, message: '请选择机构' }]" readonly :disabled="disabledFlag" />
        <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="toAddCus"
              v-if="popObj.type === 'cus'" 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="cusLevelName" v-model="popObj.cusLevelName" label="沟通等级"
          :placeholder="disabledFlag ? '' : '点击选择沟通等级'" @click="popObj.handleShowPop1('cusLevel', '沟通等级')"
          :required="!disabledFlag" :rules="[{ required: true, message: '请选择沟通等级' }]" readonly :disabled="disabledFlag"
          v-show="isAuth('communication:cus:level') && popObj.dicNote2 === '2'" />
        <van-field v-model="popObj.linkTitle" name="linkTitle" label="主题" :placeholder="disabledFlag ? '' : '请输入主题'"
          :disabled="disabledFlag"
          v-show="popObj.dicNote2 === '2' && (popObj.dicNote3 === '1' || popObj.dicNote3 === '2' || popObj.dicNote3 === '3')" />
        <van-field clickable name="cusUserNames" v-model="popObj.cusUserNames" label="联系人"
          :placeholder="disabledFlag ? '' : '点击选择联系人'" @click="popObj.handleShowPop3('cusUser', '联系人')"
          v-show="popObj.dicNote2 === '2'" :required="popObj.dicNote2 === '2' && !disabledFlag"
          :rules="[{ required: popObj.dicNote2 === '2', message: '请选择联系人' }]" readonly :disabled="disabledFlag" />
        <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>
            <div v-if="popObj.type === 'cusUser'" class="text-end primary-text-color" @click="toAddCusUser">添加联系人</div>
            <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 clickable name="staffNames" v-model="popObj.staffNames" label="研究员"
          :placeholder="disabledFlag ? '' : '点击选择研究员'" @click="popObj.handleShowPop3('staff', '研究员')"
          v-show="popObj.dicNote2 === '2' && (popObj.dicNote3 === '1' || popObj.dicNote3 === '2' || popObj.dicNote3 === '3')"
          readonly :disabled="disabledFlag" />
        <van-field clickable name="saleNames" v-model="popObj.saleNames" label="跟进人"
          :placeholder="disabledFlag ? '' : '点击选择跟进人'" @click="popObj.handleShowPop3('sale', '跟进人')"
          v-show="popObj.dicNote2 === '2' && popObj.dicNote3 !== '2'" readonly :disabled="disabledFlag" />
        <van-field clickable name="linkFromName" v-model="popObj.linkFromName" label="发起人"
          :placeholder="disabledFlag ? '' : '点击选择发起人'" @click="popObj.handleShowPop5('linkFrom', '发起人')"
          :required="popObj.dicNote3 === '1' && !disabledFlag"
          :rules="[{ required: popObj.dicNote3 === '1', message: '请选择沟通方式' }]"
          v-show="popObj.dicNote2 === '2' && (popObj.dicNote3 === '1' || popObj.dicNote3 === '2' || popObj.dicNote3 === '3')"
          readonly :disabled="disabledFlag" />
        <van-popup v-model:show="popObj.showPop6" 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.showPop6 = 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.onConfirm5">确认</van-button>
              </van-col>
            </van-row>
            <van-radio-group v-model="popObj.linkFrom" @click="popObj.changeLinkFrom">
              <van-radio :name="1">
                <div class="d-flex align-items-center">
                  <div class="radioLabel">机构人员</div>
                  <van-field class="flex-1 radioContent1 border-1 ms-10" v-model="popObj.linkFromField"
                    placeholder="录入发起人" :disabled="popObj.linkFrom !== 1" />
                </div>
              </van-radio>
              <van-radio :name="2" class="align-items-start-radio">
                <div class="d-flex align-items-start mt-10">
                  <div class="radioLabel">第一上海</div>
                  <div class="flex-1 radioContent2">
                    <van-radio-group class="ms-10" v-model="popObj.linkFromRadio" direction="horizontal"
                      :disabled="popObj.linkFrom !== 2">
                      <van-radio v-for="(item, index) in popObj.linkFromList" :key="index" :name="item.userId">
                        {{ item.userName }}
                      </van-radio>
                    </van-radio-group>
                  </div>
                </div>
              </van-radio>
            </van-radio-group>
          </div>
        </van-popup>
        <van-field clickable name="linkWayName" v-model="popObj.linkWayName" label="沟通方式"
          :placeholder="disabledFlag ? '' : '点击选择沟通方式'" @click="popObj.handleShowPop1('linkWay', '沟通方式')"
          :required="popObj.dicNote2 === '2' && !disabledFlag"
          :rules="[{ required: popObj.dicNote2 === '2', message: '请选择沟通方式' }]" readonly :disabled="disabledFlag"
          v-show="popObj.dicNote2 === '2'" />
        <van-field name="linkNote" v-model="popObj.linkNote"
          :label="popObj.dicNote3 === '1' || popObj.dicNote3 === '2' || popObj.dicNote3 === '3' ? '对方意见' : '详情'"
          :placeholder="disabledFlag ? '' : '请输入详情'"
          v-show="(popObj.dicNote2 === '1' || popObj.dicNote2 === '2') && popObj.dicNote3 !== '4'"
          :required="popObj.dicNote3 === '1' || popObj.dicNote3 === '2' || popObj.dicNote3 === '3'" :rules="[{
            required: popObj.dicNote3 === '1' || popObj.dicNote3 === '2' || popObj.dicNote3 === '3',
            message: popObj.dicNote3 === '1' || popObj.dicNote3 === '2' || popObj.dicNote3 === '3' ? '请填写对方意见' : '请填写详情'
          }]" rows="3" type="textarea" autosize :disabled="disabledFlag" />
        <van-field clickable name="meetingName" v-model="popObj.meetingName" label="相关会议"
          :placeholder="disabledFlag ? '' : '点击选择相关会议'" @click="popObj.handleShowPop2('meeting', '会议')" readonly
          :disabled="disabledFlag" v-show="popObj.dicNote3 === '5'" />
        <van-field v-model="popObj.staffNote" name="staffNote" :placeholder="disabledFlag ? '' : '请输入后续跟踪/数据反馈/沟通感想'"
          rows="3" type="textarea" autosize :disabled="disabledFlag" v-show="popObj.dicNote3 === '1'">
          <template v-slot:label>
            <div class="flex">
              <div>后续跟踪/</div>
              <div>数据反馈/</div>
              <div>沟通感想</div>
            </div>
          </template>
        </van-field>
        <div v-for="(item, index) in popObj.cusLinkStockList" :key="index" v-show="popObj.dicNote2 === '2'">
          <van-field clickable name="stockDetail" v-model="item.stockDetail" :label="`股票代码${index + 1}`"
            :placeholder="disabledFlag ? '' : '点击选择股票'" @click="popObj.handleShowPop6(index)" type="text" autosize
            readonly :disabled="disabledFlag"
            :required="popObj.dicNote3 === '1' || popObj.dicNote3 === '2' || popObj.dicNote3 === '3' || popObj.dicNote3 === '4'"
            :rules="[{
              required: popObj.dicNote3 === '1' || popObj.dicNote3 === '2' || popObj.dicNote3 === '3' || popObj.dicNote3 === '4',
              message: `请选择股票${index + 1}`
            }]" :right-icon="disabledFlag ? '' : 'close'" @click-right-icon.stop="popObj.deleteStock(index)" />
          <van-field clickable name="stockDetail" v-model="item.content" label="详情" :disabled="disabledFlag"
            type="textarea" autosize />
          <van-field name="switch" label="跟进" v-show="popObj.dicNote3 === '4'">
            <template #input>
              <van-switch v-model="item.staffCallback" size="20" :disabled="disabledFlag" />
            </template>
          </van-field>
          <van-field v-model="item.staffCallbackNote" name="staffCallbackNote" label="跟进内容" placeholder="跟进内容" rows="3"
            type="textarea" autosize v-show="popObj.dicNote3 === '4' && item.staffCallback" :disabled="disabledFlag" />
        </div>
        <van-field clickable name="stockDetail" v-model="newStockDetail" :label="`股票代码`" placeholder="点击新增股票"
          @click="popObj.handleShowPop6(-1)" autosize readonly v-show="!disabledFlag && popObj.dicNote2 === '2'" />
        <van-field name="saleScore" label="对研究员评分" v-show="popObj.dicNote3 === '1'" :disabled="disabledFlag"
          :required="popObj.dicNote3 === '1' && !disabledFlag"
          :rules="[{ required: popObj.dicNote3 === '1', message: '请选择评分' }]">
          <template #input>
            <van-rate v-model="popObj.saleScore" :count="10" />
          </template>
        </van-field>
        <van-field v-model="popObj.saleNote" name="saleNote" label="机构反馈" :placeholder="disabledFlag ? '' : '请输入机构反馈'"
          rows="3" type="textarea" autosize :disabled="disabledFlag" v-show="popObj.dicNote3 === '1'" />
        <div class="m-16 d-flex justify-content-center">
          <van-button round block type="danger" size="small" native-type="button" @click="deleteLink"
            v-if="popObj.linkId && disabledFlag && isAuth('sys:communication:delete')">
            删除
          </van-button>
          <van-button round block type="warning" size="small" native-type="button" @click="changeDisabled"
            v-if="popObj.linkId && (popObj.dicNote2 === '1' || popObj.dicNote2 === '2') && isAuth('sys:communication:update')">
            {{ disabledFlag ? '修改' : '取消' }}
          </van-button>
          <van-button v-show="!disabledFlag" 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 { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
import {
  sysDicListByType, sysUserGetStaffAndManagerList, sysUserGetSaleAndManagerList, sysUserGetCompanyUserList, cusLinkInfo,
  cusUserListByCusId, cusInfoLookUp, workMeetingLookUp, stockStockInfoLookUp, cusLinkDeleteByOne, cusLinkUpdateOrSave
} from '@/utils/api'
import { deepCopy, isAuth } from '@/utils/index'
let submitFlag = ref(false)
let stockIndex = ref(0)
let newStockDetail = ref('')
let disabledFlag = ref(true)
let axiosFlag = ref(false)
let addFlag = ref(false)
let saveFlag = ref(false)

import { debounceThrottle } from '@/mixins/debounce-throttle'
const { throttle } = debounceThrottle()
import { type CommunicateObj } from '@/utils/types'
const popObj: CommunicateObj = reactive({
  showPop1: false,
  showPop2: false,
  showPop3: false,
  showPop4: false,
  showPop5: false,
  showPop6: false,
  popTitle: '',
  type: '',
  linkId: '',
  value1: [],
  value3: [],
  value4: [],
  value5: [],
  linkTypeName: '',
  selectlinkType: '',
  linkTypeList: [],
  dicNote2: '',
  dicNote3: '',
  sysDay: '',
  selectsysDay: [],
  sysTime: '',
  selectsysTime: [],
  cusName: '',
  searchValue: '',
  showPop2List: [],
  selectcus: '',
  cusLevelName: '',
  selectcusLevel: '',
  cusLevelList: [],
  linkTitle: '',
  cusUserNames: '',
  cusUserList: [],
  selectcusUserIds: [],
  staffNames: '',
  staffList: [],
  selectstaffIds: [],
  saleNames: '',
  saleList: [],
  selectsaleIds: [],
  linkFromName: '',
  linkFrom: 1,
  linkFromRadio: '',
  linkFromField: '',
  linkFromList: [],
  linkWayName: '',
  selectlinkWay: '',
  linkWayList: [
    { value: '1', text: '见面' },
    { value: '2', text: '电话' },
    { value: '3', text: '微信' },
    { value: '4', text: '腾讯会议' }
  ],
  linkNote: '',
  meetingName: '',
  selectmeeting: '',
  staffNote: '',
  cusLinkStockList: [],
  cusLinkStockListForLinkId: [],
  saleScore: 0,
  saleNote: '',
  handleShowPop1: (val: string, title: string) => {
    if (!disabledFlag.value) {
      popObj.showPop1 = true
      popObj.popTitle = title
      popObj.type = val
      popObj.value1 = [popObj[`select${val}`]]
    }
  },
  handleShowPop2: (val: string, title: string) => {
    if (!disabledFlag.value) {
      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) => {
    if (!disabledFlag.value) {
      popObj.showPop3 = true
      popObj.popTitle = title
      popObj.type = val
      popObj.value3 = popObj[`select${val}Ids`]
    }
  },
  handleShowPop4: (val: string, title: string, index: number) => {
    if (!disabledFlag.value) {
      popObj.popTitle = title
      popObj.type = val
      popObj[`value${index}`] = popObj[`select${val}`]
      popObj[`showPop${index}`] = true
    }
  },
  handleShowPop5: (val: string, title: string) => {
    if (!disabledFlag.value) {
      if (popObj.linkFrom === 1) {
        popObj.linkFromRadio = ''
        popObj.linkFromField = popObj.linkFromName
      } else {
        const index = popObj.linkFromList.findIndex((ele: any) => {
          return ele.userName === popObj.linkFromName
        })
        if (index > -1) {
          popObj.linkFromRadio = popObj.linkFromList[index].userId
        }
      }
      popObj.showPop6 = true
      popObj.popTitle = title
      popObj.type = val
    }
  },
  handleShowPop6: (index: number) => {
    if (!disabledFlag.value) {
      popObj.showPop2 = true
      popObj.popTitle = '股票'
      popObj.type = 'stock'
      popObj.searchValue = index > -1 ? popObj.cusLinkStockList[index].stockCode : ''
      popObj.showPop2List = index > -1 ? [{ text: popObj.cusLinkStockList[index].stockName, value: popObj.cusLinkStockList[index].stockCode }] : []
      stockIndex.value = index
    }
  },
  onConfirm1: ({ selectedOptions }) => {
    if (selectedOptions) {
      popObj[`select${popObj.type}`] = selectedOptions[0].value
      popObj[`${popObj.type}Name`] = selectedOptions[0].text
      if (popObj.type === 'linkType') {
        popObj.dicNote2 = selectedOptions[0].dicNote2
        popObj.dicNote3 = selectedOptions[0].dicNote3
        setLinkTile()
      }
    }
    popObj.showPop1 = false
  },
  onSearchInput: throttle(
    async () => {
      if (popObj.searchValue) {
        if (popObj.type === 'cus') {
          const { data } = await cusInfoLookUp({ cusName: popObj.searchValue })
          popObj.showPop2List = data.map((ele: any) => {
            ele.text = ele.cusName
            ele.value = ele.cusId
            return ele
          })
        } else if (popObj.type === 'meeting') {
          const { data } = await workMeetingLookUp({ meetingTitle: popObj.searchValue })
          popObj.showPop2List = data.map((ele: any) => {
            ele.text = ele.meetingTitle
            ele.value = ele.meetingId
            return ele
          })
        } else if (popObj.type === 'stock') {
          const { data } = await stockStockInfoLookUp({ stockCode: popObj.searchValue })
          popObj.showPop2List = data.map((ele: any) => {
            ele.text = ele.stockName
            ele.value = ele.stockCode
            return ele
          })
        }
      } else {
        popObj.showPop2List = []
      }
    },
    500
  ),
  onConfirm2: ({ selectedOptions }) => {
    if (selectedOptions && selectedOptions[0]) {
      if (popObj.type === 'stock') {
        if (stockIndex.value > -1) {
          popObj.cusLinkStockList[stockIndex.value].stockCode = selectedOptions[0].value
          popObj.cusLinkStockList[stockIndex.value].stockName = selectedOptions[0].stockName
          popObj.cusLinkStockList[stockIndex.value].stockDetail = `${selectedOptions[0].value}【${selectedOptions[0].stockName}】`
        } else {
          popObj.cusLinkStockList.push({
            stockCode: selectedOptions[0].value,
            stockName: selectedOptions[0].stockName,
            content: '',
            staffCallback: false,
            staffCallbackNote: '',
            stockDetail: `${selectedOptions[0].value}【${selectedOptions[0].stockName}】`
          })
        }
      } else {
        popObj[`select${popObj.type}`] = selectedOptions[0].value
        popObj[`${popObj.type}Name`] = selectedOptions[0].text
        if (popObj.type === 'cus') {
          if (!popObj.cusLevelName) {
            popObj.cusLevelName = selectedOptions[0].cusLevelName
            popObj.selectcusLevel = selectedOptions[0].cusLevel
          }
          setLinkTile()
          popObj.cusUserNames = ''
          popObj.selectcusUserIds = []
          getCusUserList()
        }
      }
      popObj.showPop2 = false
    } else {
      showToast(`请选择${popObj.popTitle}后，再确认`)
    }
  },
  deleteStock: (index: number) => {
    if (!disabledFlag.value) {
      popObj.cusLinkStockList.splice(index, 1)
    }
  },
  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]}${popObj.type === 'sysDay' ? '-' + selectedValues[1] + '-' + selectedValues[2] : ':' + selectedValues[1]}`
      popObj[`select${popObj.type}`] = selectedValues
    }
    if (popObj.type === 'sysDay') {
      popObj.showPop4 = false
    } else {
      popObj.showPop5 = false
    }
  },
  changeLinkFrom: () => {
    if (popObj.linkFrom === 1) {
      popObj.linkFromRadio = ''
    } else if (popObj.linkFrom === 2) {
      popObj.linkFromField = ''
    }
  },
  onConfirm5: () => {
    if (popObj.linkFrom === 1) {
      popObj.linkFromName = popObj.linkFromField
      popObj.linkFromRadio = ''
      popObj.showPop6 = false
    } else if (popObj.linkFrom === 2) {
      popObj.linkFromField = ''
      const index = popObj.linkFromList.findIndex((ele: any) => {
        return ele.userId === popObj.linkFromRadio
      })
      if (index > -1) {
        popObj.linkFromName = popObj.linkFromList[index].userName
        popObj.showPop6 = false
      } else {
        showToast('请选择发起人')
      }
    }
  }
})

import saveCommunicateInfoStore from '@/stores/saveCommunicateInfo'
const saveCommunicateInfo: any = saveCommunicateInfoStore()
import saveInfoStore from '@/stores/saveInfo'
const saveInfo: any = saveInfoStore()
import userInfoStore from '@/stores/userInfo'
const userInfo = userInfoStore()
const getSelectList = async () => {
  emitter.emit('showLoading', '')
  // const data1 = await sysDicListByType({ dicType: 'link_type' })
  // popObj.linkTypeList = data1.data.map((ele: any) => {
  //   ele.text = ele.dicValue
  //   ele.value = ele.dicKey
  //   return ele
  // })
  if (userInfo.roleId === '1' || userInfo.roleId === '9') {
    popObj.linkTypeList = [{
      dicKey: '34',
      dicValue: '机构沟通',
      text: '机构沟通',
      value: '34',
      dicNote: '3',
      dicNote2: '2',
      dicNote3: '2'
    }, {
      dicKey: '32',
      dicValue: '机构路演',
      text: '机构路演',
      value: '32',
      dicNote: '3',
      dicNote2: '2',
      dicNote3: '1'
    }, {
      dicKey: '31',
      dicValue: '上市公司按需会议',
      text: '上市公司按需会议',
      value: '31',
      dicNote: '3',
      dicNote2: '2',
      dicNote3: '3'
    }]
  } else if (userInfo.roleId === '10') {
    popObj.linkTypeList = [{
      dicKey: '32',
      dicValue: '机构路演',
      text: '机构路演',
      value: '32',
      dicNote: '3',
      dicNote2: '2',
      dicNote3: '1'
    }, {
      dicKey: '31',
      dicValue: '上市公司按需会议',
      text: '上市公司按需会议',
      value: '31',
      dicNote: '3',
      dicNote2: '2',
      dicNote3: '3'
    }]
  } else if (userInfo.roleId === '6' || userInfo.roleId === '7' || userInfo.roleId === '16') {
    popObj.linkTypeList = [{
      dicKey: '34',
      dicValue: '机构沟通',
      text: '机构沟通',
      value: '34',
      dicNote: '3',
      dicNote2: '2',
      dicNote3: '2'
    }, {
      dicKey: '31',
      dicValue: '上市公司按需会议',
      text: '上市公司按需会议',
      value: '31',
      dicNote: '3',
      dicNote2: '2',
      dicNote3: '3'
    }]
  }
  const data2 = await sysDicListByType({ dicType: 'cus_level' })
  popObj.cusLevelList = data2.data.map((ele: any) => {
    ele.text = ele.dicValue
    ele.value = ele.dicKey
    return ele
  })
  const data3 = await sysUserGetStaffAndManagerList()
  popObj.staffList = data3.data.map((ele: any) => {
    ele.value = ele.userId
    ele.text = ele.userName
    return ele
  })
  const data4 = await sysUserGetSaleAndManagerList()
  popObj.saleList = data4.data.map((ele: any) => {
    ele.value = ele.userId
    ele.text = ele.userName
    return ele
  })
  const data5 = await sysUserGetCompanyUserList()
  popObj.linkFromList = data5.data
  if (route.query && route.query.linkId) {
    popObj.linkId = route.query.linkId?.toString() || ''
    getLinkInfo()
  } else if (route.query && route.query.addDay) {
    let day = moment(route.query.addDay + '').format('YYYY-MM-DD HH:mm:ss')
    initData(day)
  } else {
    let nowDay = moment().format('YYYY-MM-DD HH:mm:ss')
    initData(nowDay)
  }
}

const initData = (day: any) => {
  addFlag.value = true
  let sale = popObj.saleList.find((ele: any) => {
    return ele.userId === userInfo.id
  })
  if (sale && !saveCommunicateInfo.saleNames) {
    saveCommunicateInfo.saleNames = sale.userName
    saveCommunicateInfo.selectsaleIds = [sale.userId]
  }
  saveCommunicateInfo.sysDay = day.slice(0, 10)
  saveCommunicateInfo.selectsysDay = day.slice(0, 10).split('-')
  saveCommunicateInfo.sysTime = day.slice(11, 16)
  saveCommunicateInfo.selectsysTime = day.slice(11, 16).split(':')
  if (!saveCommunicateInfo.linkTypeName) {
    if (userInfo.roleId === '1' || userInfo.roleId === '9') {
      saveCommunicateInfo.linkTypeName = '机构路演'
      saveCommunicateInfo.selectlinkType = '32'
      saveCommunicateInfo.dicNote2 = '2'
      saveCommunicateInfo.dicNote3 = '1'
    } else if (userInfo.roleId === '10') {
      saveCommunicateInfo.linkTypeName = '机构路演'
      saveCommunicateInfo.selectlinkType = '32'
      saveCommunicateInfo.dicNote2 = '2'
      saveCommunicateInfo.dicNote3 = '1'
    } else if (userInfo.roleId === '6' || userInfo.roleId === '7' || userInfo.roleId === '16') {
      saveCommunicateInfo.linkTypeName = '机构沟通'
      saveCommunicateInfo.selectlinkType = '34'
      saveCommunicateInfo.dicNote2 = '2'
      saveCommunicateInfo.dicNote3 = '1'
    }
  }
  if (!saveCommunicateInfo.linkFromName) {
    saveCommunicateInfo.linkFrom = 2
    let user = popObj.linkFromList.find((ele: any) => {
      return ele.userId === userInfo.id
    })
    console.log(user)
    if (user) {
      saveCommunicateInfo.linkFromRadio = user.userId
      saveCommunicateInfo.linkFromName = user.userName
    }
  }
  for (let i in saveCommunicateInfo) {
    if (Object.prototype.hasOwnProperty.call(popObj, i)) {
      popObj[i] = saveCommunicateInfo[i]
    }
  }
  saveAddData()
  emitter.emit('setTitle', { title: '新增沟通', type: 'communicate' })
  emitter.emit('hiddenLoading', '')
  disabledFlag.value = false
}

const saveAddData = () => {
  if (saveInfo.id) {
    if (saveInfo.type === 'cus') {
      popObj.cusName = saveInfo.name
      popObj.selectcus = saveInfo.id
      popObj.cusUserNames = ''
      popObj.selectcusUserIds = []
      popObj.cusUserList = []
      getCusUserList()
    } else {
      popObj.cusUserNames = popObj.cusUserNames ? `${popObj.cusUserNames},${saveInfo.name}` : saveInfo.name
      popObj.selectcusUserIds.push(saveInfo.id)
      if (popObj.selectcus) {
        getCusUserList()
      }
    }
    saveInfo.name = ''
    saveInfo.id = ''
    saveInfo.type = ''
  } else {
    if (popObj.selectcus) {
      getCusUserList()
    }
  }
}

import updateCommunicateInfoStore from '@/stores/updateCommunicateInfo'
const updateCommunicateInfo: any = updateCommunicateInfoStore()
const getLinkInfo = async () => {
  if (updateCommunicateInfo.linkTypeName) {
    disabledFlag.value = false
    for (let i in updateCommunicateInfo) {
      if (updateCommunicateInfo[i] && Object.prototype.hasOwnProperty.call(popObj, i)) {
        popObj[i] = updateCommunicateInfo[i]
      }
    }
    emitter.emit('setTitle', { title: popObj.linkTitle, type: 'communicate' })
    saveAddData()
  } else {
    const { data } = await cusLinkInfo(popObj.linkId)
    emitter.emit('setTitle', { title: data.linkTitle, type: 'communicate' })
    popObj.linkTypeName = data.linkTypeName
    popObj.selectlinkType = data.linkType
    const res: any = popObj.linkTypeList.find((ele: any) => {
      return ele.dicKey === data.linkType
    })
    popObj.dicNote2 = res.dicNote2
    popObj.dicNote3 = res.dicNote3
    popObj.sysDay = data.sysDate.slice(0, 10)
    popObj.selectsysDay = popObj.sysDay.split('-')
    popObj.sysTime = data.sysDate.slice(11, 16)
    popObj.selectsysTime = popObj.sysTime.split(':')
    popObj.cusName = data.cusName
    popObj.selectcus = data.cusId
    popObj.cusLevelName = data.cusLevelName
    popObj.selectcusLevel = data.cusLevel
    popObj.linkTitle = data.linkTitle
    getCusUserList()
    popObj.cusUserNames = data.cusUserName
    popObj.selectcusUserIds = data.cusUserId ? data.cusUserId.split(',').map(Number) : []
    popObj.staffNames = data.staffName
    popObj.selectstaffIds = data.staffId ? data.staffId.split(',').map(Number) : []
    popObj.saleNames = data.saleNames
    popObj.selectsaleIds = data.saleIds ? data.saleIds.split(',').map(Number) : []
    popObj.linkFrom = data.linkFromId && data.linkFromId !== -1 ? 2 : 1
    popObj.linkFromName = data.linkFrom
    popObj.linkWayName = data.linkWayName
    popObj.selectlinkWay = data.linkWay + ''
    popObj.linkNote = data.linkNote
    popObj.meetingName = data.meetingTitle
    popObj.selectmeeting = data.meeting_id
    popObj.staffNote = data.staffNote
    popObj.cusLinkStockList = data.cusLinkStockList.map((ele: any) => {
      let res = {
        stockCode: ele.stockCode,
        stockName: ele.stockName,
        content: ele.content,
        staffCallback: !!ele.staffCallback,
        staffCallbackUserName: ele.staffCallbackUserName,
        staffCallbackUserId: ele.staffCallbackUserId,
        staffCallbackTime: ele.staff_callback_time,
        staffCallbackNote: ele.staff_callback_note,
        id: ele.id,
        stockDetail: `${ele.stockCode}${ele.stockName ? '【' + ele.stockName + '】' : ''}`
      }
      return res
    })
    popObj.cusLinkStockListForLinkId = deepCopy(popObj.cusLinkStockList)
    popObj.saleScore = data.saleScore || 0
    popObj.saleNote = data.saleNote
  }
  emitter.emit('hiddenLoading', '')
}

const getCusUserList = async () => {
  const { data } = await cusUserListByCusId({ cusId: popObj.selectcus })
  data.map((ele: any) => {
    ele.value = ele.cusUserId
    ele.text = `${ele.cusUserName}${ele.positionName ? '【' + ele.positionName + '】' : ''}`
  })
  popObj.cusUserList = data
}

const setLinkTile = () => {
  if (!popObj.linkTitle && popObj.cusName && popObj.linkTypeName) {
    popObj.linkTitle = popObj.cusName + '-' + popObj.linkTypeName
  }
}

import listRefreshInfoStore from '@/stores/listRefreshInfo'
const listRefreshInfo = listRefreshInfoStore()
const deleteLink = () => {
  showConfirmDialog({
    title: '提示',
    message:
      `是否确认删除在${popObj.sysDay} ${popObj.sysTime}与${popObj.cusName}的${popObj.linkTypeName}`,
  }).then(async () => {
    const data: any = await cusLinkDeleteByOne({ linkId: popObj.linkId })
    if (data.code === 0) {
      axiosFlag.value = true
      showToast('删除成功')
      listRefreshInfo.deleteId = popObj.linkId
      router.replace({ name: 'communicate-list' })
    }
  }).catch(() => {
  })
}

const changeDisabled = () => {
  disabledFlag.value = !disabledFlag.value
  if (disabledFlag.value) {
    getLinkInfo()
  }
}

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

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

onUnmounted(() => {
  if (addFlag.value) {
    if (axiosFlag.value) {
      saveCommunicateInfo.$reset()
      saveCommunicateInfo.selectlinkType = popObj.selectlinkType
      saveCommunicateInfo.linkTypeName = popObj.linkTypeName
    } else {
      for (let i in saveCommunicateInfo) {
        if (Object.prototype.hasOwnProperty.call(popObj, i)) {
          saveCommunicateInfo[i] = popObj[i]
        }
      }
    }
  } else {
    if (saveFlag.value) {
      for (let i in updateCommunicateInfo) {
        if (Object.prototype.hasOwnProperty.call(popObj, i)) {
          updateCommunicateInfo[i] = popObj[i]
        }
      }
    } else {
      updateCommunicateInfo.$reset()
    }
  }
  window.removeEventListener('keyup', handleKeyUp)
})

const toAddCus = () => {
  saveFlag.value = true
  if (popObj.linkId) {
    router.push({ name: 'add-cus', query: { linkId: popObj.linkId } })
  } else {
    router.push({ name: 'add-cus' })
  }
}

const toAddCusUser = () => {
  if (popObj.selectcus) {
    saveFlag.value = true
    router.push({ name: 'add-cusUser', query: { cusId: popObj.selectcus, linkId: popObj.linkId, from: 'detail' } })
  } else {
    showToast('请先选择机构')
  }
}

const onSubmit = async () => {
  if (!disabledFlag.value) {
    submitFlag.value = true
    let cusLinkCusUserList: any = []
    let stockList: any = []
    if (popObj.dicNote2 === '2') {
      const sameCusUserList = popObj.cusUserList.filter(
        (res: any) => popObj.selectcusUserIds.some((ele: any) => res.cusUserId === ele)
      )
      sameCusUserList.forEach(ele => {
        cusLinkCusUserList.push({
          cusUserId: ele.value,
          cusUserName: ele.text
        })
      })
      const sameStockList = popObj.cusLinkStockList.filter(
        (res: any) => popObj.cusLinkStockListForLinkId.some((ele: any) => res.stockCode === ele.stockCode)
      )
      sameStockList.forEach((ele: any) => {
        if (ele.stockCode) {
          const stockData: any = popObj.cusLinkStockListForLinkId.find((res: any) => { return res.stockCode === ele.stockCode })
          stockList.push({
            stockCode: ele.stockCode,
            stockName: ele.stockName,
            stockCompanyType: ele.stockCompanyType,
            staffCallback: ele.staffCallback ? 1 : 0,
            content: ele.content,
            id: stockData.id
          })
        }
      })
      const differentStockList = popObj.cusLinkStockList.filter(
        (res: any) => !popObj.cusLinkStockListForLinkId.some((ele: any) => res.stockCode === ele.stockCode)
      )
      differentStockList.forEach((ele: any) => {
        if (ele.stockCode) {
          stockList.push({
            stockCode: ele.stockCode,
            stockName: ele.stockName,
            stockCompanyType: ele.stockCompanyType,
            staffCallback: ele.staffCallback ? 1 : 0,
            content: ele.content
          })
        }
      })
    }
    const res: any = {
      linkType: popObj.selectlinkType,
      sysDate: `${popObj.sysDay} ${popObj.sysTime}:00`,
      cusId: popObj.selectcus,
      cusName: popObj.cusName,
      cusLevel: popObj.selectcusLevel || 'E',
      linkTitle: popObj.linkTitle,
      cusLinkCusUserList: cusLinkCusUserList,
      staffList: popObj.selectstaffIds,
      saleList: popObj.selectsaleIds,
      linkFrom: popObj.linkFromName || null,
      linkFromId: popObj.linkFrom === 2 && popObj.linkFromRadio ? popObj.linkFromRadio : null,
      linkWay: popObj.selectlinkWay,
      linkNote: popObj.linkNote || null,
      meetingId: popObj.selectmeeting || null,
      staffNote: popObj.staffNote || null,
      cusLinkStockList: stockList,
      saleScore: popObj.saleScore || null,
      saleNote: popObj.saleNote || null,
      dataFrom: 2
    }
    if (popObj.linkId) {
      res.linkId = popObj.linkId
    }
    const data: any = await cusLinkUpdateOrSave(popObj.linkId, res)
    if (data.code === 0) {
      axiosFlag.value = true
      showToast('提交成功')
      if (popObj.linkId) {
        listRefreshInfo.refreshId = popObj.linkId
      } else {
        listRefreshInfo.addId = '1'
      }
      router.go(-1)
    } else {
      submitFlag.value = false
    }
  }
}

getSelectList()
</script>

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

.detailClass1 {
  .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;
    }
  }
}

.detailClass2 {
  .van-cell {
    margin: 0 16px;
    width: calc(100vw - 32px);
    box-shadow: 0 0;
    @media screen and (min-width: 678px) {
      width: 646px;
    }
  }
}

:deep(.van-field--disabled) .van-field__label {
  color: #646566;
}

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

.box-popup {
  :deep(.van-field__control:disabled) {
    -webkit-text-fill-color: #c8c9cc !important;
  }
}

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

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

:deep(.van-radio) {
  width: 100%;
}

.radioLabel {
  width: 60px;
}

.radioContent1 {
  max-width: 220px;
  margin-left: 10px !important;
}

.radioContent2 {
  max-height: 400px;
  overflow-y: auto;

  .van-radio {
    margin-right: 0 !important;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    width: 50%;
    margin-bottom: 5px;
  }
}

:deep(.align-items-start-radio) {
  align-items: flex-start !important;
  max-height: 300px;

  .van-radio__icon {
    margin-top: 10px;
  }
}

:deep(.van-icon-star-o),
:deep(.van-rate__icon) {
  font-size: 16px;
}

.van-radio-group {
  .van-cell {
    margin-top: 0;
  }
}

:deep(.ms-10) {
  .van-radio__icon {
    margin-top: 0;
  }
}
</style>
