<template>
  <div class="order-list">
    <BasicTable @register="registerTable">
      <template #form-age>
        <div class="flex-row">
          <InputNumber placeholder="请输入" style="width: 46%" v-model:value="ageModel.minAge" />
          <div style="width: 8%" class="flex-row-center-center">-</div>
          <InputNumber placeholder="请输入" style="width: 46%" v-model:value="ageModel.maxAge" />
        </div>
      </template>
      <template #toolbar>
        <div style="width: 100%; padding: 2px" class="flex-row-center-space">
          <RadioGroup button-style="solid" v-model:value="radioVal" @change="handleRadioChange">
            <RadioButton v-for="item in clueStatusList" :key="item.value" :value="item.value">{{item.label}}</RadioButton>
          </RadioGroup>
          <div class="flex-row-center-start">
            <Popconfirm placement="bottom" icon="分配线索" :disabled="datingClueIdList.length == 0" @confirm="allocateList(null)">
              <template #title>
                <div class="flex-row-center-start" style="padding: 8px 8px 8px 0px;border-bottom: 1px solid #ddd;" v-for="item in memberList" :key="item.userId">
                  <Checkbox :checked="verifier == item.userId" @change="e => onCheckChange(e, item)">
                    <span style="color: #333;font-weight: bold;margin-left: 4px;">{{item.realName}}</span>
                    <span style="color: #666;margin-left: 4px;">({{item.phone}})</span>
                  </Checkbox>
                </div>
              </template>
              <Button type="primary" danger :disabled="datingClueIdList.length == 0">分配</Button>
            </Popconfirm>
            <Button style="margin-left: 16px;" @click="handleAdd(true)">批量导入</Button>
            <Button :type="'primary'" style="margin-left: 16px;" @click="handleAdd(false)">新增</Button>
          </div>
        </div>
      </template>
      <template #userinfo="{ text, record }">
        <div class="flex-row">
          <Image style="width: 40px;height: 40px;" :src="record.profilePhoto || 'https://dating-agency-prod.oss-cn-shenzhen.aliyuncs.com/827036501B11.png'" />
          <div class="flex-col" style="margin-left: 8px;">
            <div class="flex-row">
              <span class="single-line" style="font-size: 14px;color: #333;font-weight: bold;max-width: 160px;">{{record.nickName}}</span>
              <!-- <span class="single-line" style="font-size: 13px;color: #666;margin: 0 12px;">(ID：{{record.id}})</span> -->
            </div>
            <div class="flex-row">
              <span style="font-size: 13px;color: #666;" v-if="record.age">{{record.age}}岁</span>
              <span style="font-size: 13px;color: #666;margin-left: 12px;">{{educationList.find((find) => find.value === record.educationCode)?.label}}</span>
              <span style="font-size: 13px;color: #666;margin-left: 12px;">{{maritalList.find((find) => find.value === record.maritalStatusCode)?.label}}</span>
              <span style="font-size: 13px;color: #666;margin-left: 12px;" v-if="record.occupation">{{record.occupation}}</span>
            </div>
          </div>
        </div>
      </template>
      <template #action="{ record }">
        <!-- <TableAction
          :actions="[
            {
              label: '详情',
              onClick: toDetail.bind(null, record),
            },
          ]"
        /> -->
        <div class="flex-row-center-start">
          <Button type="link" @click="toDetail(record)">详情</Button>
          <span style="color: #999;">|</span>
          <Popconfirm placement="topRight" :icon="record.allocationStatus == 1 ? '分配' : '重新分配'" @confirm="allocateList(record.id)">
            <template #title>
              <div class="flex-row-center-start" style="padding: 8px 8px 8px 0px;border-bottom: 1px solid #ddd;" v-for="item in memberList" :key="item.userId">
                <Checkbox :checked="verifier == item.userId" @change="e => onCheckChange(e, item)">
                  <span style="color: #333;font-weight: bold;margin-left: 4px;">{{item.realName}}</span>
                  <span style="color: #666;margin-left: 4px;">({{item.phone}})</span>
                </Checkbox>
              </div>
            </template>
            <Button type="link" danger >{{record.allocationStatus == 1 ? '分配' : '重新分配'}}</Button>
          </Popconfirm>
        </div>
      </template>
    </BasicTable>
  </div>
</template>

<script lang="ts">
  import { Radio } from 'ant-design-vue'

  export default {
    name: 'MyClue',
    components: { RadioGroup: Radio.Group, RadioButton: Radio.Button },
  }
</script>
<script setup lang="ts">
  import moment from 'moment/moment'
  import { onMounted, reactive, ref } from 'vue'
  import { Card, Image, Button, InputNumber, Popconfirm, Checkbox } from 'ant-design-vue'
  import { useRouter } from 'vue-router'
  import { useMessage } from '/@/hooks/web/useMessage'
  import { tableColumns, tableFormSchema } from './data'
  import { useModal } from '/@/components/Modal'
  import { BasicTable, useTable, TableAction } from '/@/components/Table'
  import { getInvitationList, allocateCluing } from '/@/api/clue'
  import { pageOrganizationMember } from '/@/api/staff/staff'
  import { educationList, maritalList } from '/@/enums/customerEnum'

  const radioVal = ref<any>('')
  const verifier = ref<any>('')

  const clueStatusList = [
    { label: '待分配', value: 1 },
    { label: '跟进中', value: 2 },
    { label: '公海线索', value: 3 },
    { label: '全部', value: '' },
  ]

  const ageModel = reactive({
    minAge: '',
    maxAge: '',
  })

  const memberList = ref<any[]>([]);

  onMounted(async () => {
    const result = await pageOrganizationMember({})
    memberList.value = result.items
  })

  const [registerTable, { reload, setPagination, getSelectRowKeys, clearSelectedRowKeys }] = useTable({
    bordered: true,
    useSearchForm: true,
    columns: tableColumns,
    showIndexColumn: true,
    showTableSetting: false,
    api: getInvitationList,
    // rowKey: 'id',
    // rowSelection: {
    //   type: 'checkbox',
    //   onChange,
    //   getCheckboxProps(record: Recordable) {
    //     // Demo: 第一行（id为0）的选择框禁用
    //     return { disabled: record.allocationStatus !== 1 };
    //   },
    // },
    formConfig: {
      labelWidth: 120,
      schemas: tableFormSchema,
    },
    beforeFetch: (arg) => {
      const { createTime, followTime } = arg
      if (createTime) {
        arg.creatTimeFrom = moment(createTime[0]).format('YYYY-MM-DD 00:00:00')
        arg.creatTimeTo = moment(createTime[1]).format('YYYY-MM-DD 23:59:59')
        delete arg.createTime
      }
      if (followTime) {
        arg.finalFollowTimeFrom = moment(followTime[0]).format('YYYY-MM-DD 00:00:00')
        arg.finalFollowTimeTo = moment(followTime[1]).format('YYYY-MM-DD 23:59:59')
        delete arg.followTime
      }
      arg.minimumAge = ageModel.minAge
      arg.maximumAge = ageModel.maxAge
      arg.allocationStatus = radioVal.value
    },
    actionColumn: {
      width: 160,
      title: '操作',
      fixed: 'right',
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  })

  function handleRadioChange() {
    setPagination({ current: 1 })
    datingClueIdList.value = []
    reload()
  }

  const [registerModal, { openModal, closeModal }] = useModal()
  function handleAdd(excel) {
    openModal(true, {ifUpdate: excel,})
  }
  // 操作成功
  function handleSuccess() {
    closeModal()
    reload()
  }
  const { createMessage } = useMessage()
  const router = useRouter()
  function toDetail(record: any) {
    const { id } = record
    router.push({
      query: { id },
      path: '/clue/customer',
    })
  }
  const datingClueIdList = ref<string[]>([]);
  function onChange(selectedRowKeys) {
    datingClueIdList.value = selectedRowKeys
  }
  function onCheckChange(e, item){
    if(e.target.checked){
      verifier.value = item.userId
    }
  }
  async function allocateList(id = null){
    if(!verifier.value){
      createMessage.warning('请选择分配人')
      return
    }
    var datingClueIdList: string[] = []
    if(id){
      datingClueIdList = [id]
    } else {
      datingClueIdList = getSelectRowKeys()
    }
    try {
      await allocateCluing({verifier: verifier.value, datingClueIdList})
      createMessage.success(`分配成功`)
      clearSelectedRowKeys()
    } finally {
      reload()
    }
  }
</script>
<style scoped lang="less">
.single-line {
  overflow: hidden; /* 超出部分隐藏 */
  white-space: nowrap; /* 文本不换行 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
}
</style>
