<template>
  <div class="page-search row items-center" v-if="select.length==0">
    <div class="col row wrap q-mr-lg q-col-gutter-md">
      <div class="col-3">
        <q-input filled v-model="SeletObj.selectVal" clearable dense @clear="clearSelectWay"
          @update:model-value="getSelectWay" placeholder="请输入">
          <template #before>
            <div style="border-right: 1px solid #999;padding-right:0">
              <q-select filled @update:model-value="getSelectWay" option-value="Id" option-label="Name" dense
                v-model="SeletObj.selectWay" :options="TypeList" emit-value map-options />
            </div>
          </template>
        </q-input>
      </div>
      <div class="flex no-wrap">
        <q-select filled option-value="Id" option-label="Name" v-model="TimeObj.timeWay" :options="TimeList" dense
          emit-value map-options @update:model-value="changeTime"> </q-select>
        <n-config-provider :locale="zhCN" :date-locale="dateZhCN">
          <n-date-picker v-model:value="TimeObj.timeRange" type="datetimerange" size="small" separator="至" clearable
            class="full-height" @update:value='changeTimeRange' />
        </n-config-provider>
      </div>
      <div class="col-2">
        <n-cascader v-model:value="CascaderData.customerCascaderValue" clearable placeholder="客户筛选"
          check-strategy="child" size="large" :show-path="false" max-tag-count="responsive" multiple
          :options="CustomList" cascade />
      </div>
      <div class="col-2">
        <n-cascader v-model:value="CascaderData.deptCascaderValue" clearable placeholder="选择部门/人员" check-strategy="all"
          value-field="newId" label-field="DeptName" size="large" :show-path="false" max-tag-count="responsive"
          :options="EmployeeList" cascade children-field="ChildList" @update:value="getDept" />
      </div>
      <div class="col-2">
        <vt-custom-btn ref="vtBtn" :page-code="pageCode" :columns="columns" @empty-where="deleteWhereHandler(0)"
          @update-where="updateWhereHandler"></vt-custom-btn>
        <!-- <q-btn class="q-ml-md q-px-md" color="dark" label="重置" dense outline @click="deleteWhereHandler(1)"></q-btn> -->
      </div>
      <div class="col-2">
        <q-btn-dropdown label="导入" dense color="primary">
          <q-list>
            <q-item>
              <q-btn unelevated dense label="导入个人客户" @click="showImport=true" />
            </q-item>
            <q-item>
              <q-btn unelevated dense label="导入企业客户" />
            </q-item>
          </q-list>
        </q-btn-dropdown>
        <q-btn-dropdown label="导出" color="primary" dense class="q-ml-md">
          <q-list>
            <q-item>
              <q-btn unelevated dense label="导出个人客户" />
            </q-item>
            <q-item>
              <q-btn unelevated dense label="导出企业客户" />
            </q-item>
          </q-list>
        </q-btn-dropdown>
      </div>
    </div>
  </div>
  <div class="select-navs row q-mb-md q-pa-sm flex justify-between items-center" v-if="select.length>0">
    <div class="flex items-center">
      <div style="color: #111;font-weight:bold">已选择{{select.length}}项</div>
      <q-btn style="background-color: #fff; color: #606266" unelevated outline label="设置标签" class="q-ml-md"
        @click="showDialog('isshowlabel')" />
      <q-btn style="background-color: #fff; color: #606266" unelevated outline label="放弃" class="q-ml-md"
        @click="showDialog('showAbandon')" />
      <q-btn style="background-color: #fff; color: #606266" unelevated outline label="转移" class="q-ml-md"
        @click="showDialog('showTransfer')" />

      <q-btn-dropdown label="导出" outline style="background-color: #fff; color: #606266" class="q-ml-md">
        <q-list>
          <q-item>
            <q-btn unelevated dense label="导出客户" />
          </q-item>
          <q-item>
            <q-btn unelevated dense label="导出标签记录" />
          </q-item>
        </q-list>
      </q-btn-dropdown>
      <q-btn style="background-color: #FFEDED; color: #FF4949" unelevated outline label="彻底删除" class="q-ml-md"
        @click="delCustomer" />
    </div>
    <q-icon name="cancel" size="sm" style="color:#707070" @click="closeSel"></q-icon>
  </div>
  <div>
    <labelgroup v-model="isshowlabel" @submit="getlabel"></labelgroup>
    <importComponents v-model="showImport" @confirm="getFile">
      <template #head>
        <q-tabs v-model="importTab" dense class="text-grey" align="left" active-color="primary"
          indicator-color="primary" narrow-indicator>
          <q-tab :name="1" label="直接分配负责人" />
          <q-tab :name="2" label="上传后再分配负责人" />
        </q-tabs>
      </template>
      <template #top>
        <div v-if="importTab==1">表格中需添加负责人“企微账号” </div>
        <div v-if="importTab==2">仅限于客户库可重复模式下使用 </div>
      </template>
      <template #bottom>
        <div class="full-width bottom-slot" v-if="importTab==2">
          <div class="row no-wrap">
            <div class="col-1 add-dep-left">分配员工:</div>
            <div class="col-11">
              <q-btn outline unelevated size="14px" color="primary" label="选择" class="q-mb-sm"
                @click="showDptDialog=true" />
              <div>
                <q-chip color="primary" v-for="(item,index) in DptDialogArr" :key="index" text-color="white"
                  :icon="item.Type==1?'work':'person'" :label="item.DeptName"></q-chip>
              </div>
            </div>
          </div>
          <div class="row no-wrap">
            <div class="col-1 add-dep-left">分配规则:</div>
            <div class="col-11">
              <q-radio dense v-model="DistributionRule" :val="1" label=" 按已选员工顺序依次轮流分配 " class="q-mt-sm" /><br />
              <q-radio dense v-model="DistributionRule" :val="2" label=" 按已选员工随机分配 " class="q-mt-sm" />
            </div>
          </div>
        </div>
      </template>
    </importComponents>
    <departmentStaff v-model="showDptDialog" :defaultArray="[]" nodeKey="newId" labelKey="DeptName"
      childrenKey="ChildList" strategy="leaf" :treeData="EmployeeList" @select="getDeptDig" />
    <!-- ----------------转移客户-------------------------- -->
    <q-dialog v-model="showTransfer" class="col-6" persistent>
      <q-card style="width: 480px;  max-width: 80vw">
        <q-card-section class="row items-center q-pb-none">
          <div class="text-h6">转移客户</div>
          <q-space />
          <q-btn icon="close" flat round dense v-close-popup />
        </q-card-section>

        <q-card-section class="q-pt-none">
          <div class="row q-my-md flex items-center no-wrap" style="white-space:nowrap">
            转移给：
            <n-cascader v-model:value="TransferMsg.EmpId" clearable placeholder="客户筛选" check-strategy="child"
              size="large" :show-path="false" max-tag-count="responsive" :options="EmployeeList" cascade
              value-field="DeptId" label-field="DeptName" children-field="ChildList" />
          </div>
          <div>
            90个自然日内，在职成员的每位客户仅可被转接2次。
          </div>
        </q-card-section>

        <q-card-actions align="right" class="bg-white text-teal">
          <q-btn flat label="取消" v-close-popup />
          <q-btn color="primary" unelevated label="确定" @click="setTransfer" />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <!-- ----------------放弃客户-------------------------- -->
    <q-dialog v-model="showAbandon" class="col-6" persistent>
      <q-card style="width: 480px;  max-width: 80vw">
        <q-card-section class="row items-center q-pb-none">
          <div class="text-h6">放弃客户</div>
          <q-space />
          <q-btn icon="close" flat round dense v-close-popup />
        </q-card-section>

        <q-card-section class="q-pt-none">
          <div class="row q-my-md flex  no-wrap" style="white-space:nowrap">
            <q-input outlined v-model="AbandonMsg.Reason" label="放弃原因：" dense type="textarea" style="width:100%" />
          </div>
          <div>
            放弃后，客户将进入公海
          </div>
          <div>
            审批人 审批人为空（您所在部门没有设置主管），将自动通过审批
          </div>
        </q-card-section>

        <q-card-actions align="right" class="bg-white text-teal">
          <q-btn flat label="取消" v-close-popup />
          <q-btn color="primary" unelevated label="确定" @click="setAbandon" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script>
  import {
    reactive,
    ref,
    inject,
    toRefs
  } from 'vue'
  import {
    zhCN,
    dateZhCN
  } from 'naive-ui'
  import dayjs from 'dayjs'
  import message from '@/utils/message'
  import { Dialog } from 'quasar'
  import customerService from '@/api/customer'
  import vtCustomBtn from '../common/customWhere/vtCustomBtn.vue'
  import labelgroup from '@/components/customer/label-group.vue'
  import importComponents from '@/components/common/import.vue'
  import departmentStaff from '@/components/common/departmentStaff.vue'
  export default {
    props: {
      /**
       * @description 模式：0为未选择表格内容模式，1为选中了表格内容模式
       */
      select: {
        type: Array,
        default: () => []
      },

      /**
       * @description 列数组
       */
      columns: Array,
      EmployeeList: {
        type: Array,
        default: () => []
      },
    },
    components: {
      vtCustomBtn,
      labelgroup,
      importComponents,
      departmentStaff
    },
    setup(props, ctx) {
      const updatePage = () => {
        ctx.emit('update')
      }
      const msg = inject('msg')
      console.log('msg', msg)
      const pageCode = ref('clue_custom')
      const vtBtn = ref(null)
      const SeletObj = reactive({
        selectVal: '',
        selectWay: 0
      })
      const TimeObj = reactive({
        timeWay: 1,
        timeRange: null
      })
      //选择方式
      const getSelectWay = () => {
        msg.CorpName = ''
        msg.WeChatName = ''
        msg.CustomerName = ''
        msg.CustomerMobile = ''
        //1企业名称 2姓名 3备注名 4手机号
        if (SeletObj.selectWay == 0) {
          msg.CorpName = SeletObj.selectVal
        }
        if (SeletObj.selectWay == 1) {
          msg.WeChatName = SeletObj.selectVal
        }
        if (SeletObj.selectWay == 2) {
          msg.CustomerName = SeletObj.selectVal
        }
        if (SeletObj.selectWay == 3) {
          msg.CustomerMobile = SeletObj.selectVal
        }
        ctx.emit('update')
      }

      const clearSelectWay = () => {
        msg.CorpName = ''
        msg.WeChatName = ''
        msg.CustomerName = ''
        msg.CustomerMobile = ''
      }
      const TypeList = reactive([{
          Name: '企业',
          Id: 0
        },
        {
          Name: '昵称',
          Id: 1
        },
        {
          Name: '备注名',
          Id: 2
        },
        {
          Name: '电话',
          Id: 3
        }
      ])
      const TimeList = reactive([{
          Name: '客户创建时间',
          Id: 1
        },
        {
          Name: '好友添加时间',
          Id: 2
        }
      ])
      //切换时间范围
      const changeTime = () => {
        msg.FriendSTime = ''
        msg.FriendETime = ''
        msg.CreateSTime = ''
        msg.CreateETime = ''
        TimeObj.timeRange = null
      }
      //选择时间范围
      const changeTimeRange = val => {
        if (val) {
          const s = dayjs(val[0]).format('YYYY-MM-DD HH:mm:ss')
          const e = dayjs(val[1]).format('YYYY-MM-DD HH:mm:ss')
          if (TimeObj.timeWay == 1) {
            msg.CreateSTime = s
            msg.CreateETime = e
          } else {
            msg.FriendSTime = s
            msg.FriendETime = e
          }
        } else {
          msg.FriendSTime = ''
          msg.FriendETime = ''
          msg.CreateSTime = ''
          msg.CreateETime = ''
        }
        ctx.emit('update')
      }
      //客户筛选列表
      const CustomList = reactive([{
          label: '好友关系',
          value: '1',
          children: [{
              label: '未添加',
              value: '1-1'
            },
            {
              label: '已添加',
              value: '1-2'
            }
          ]
        },
        {
          label: '获取途径',
          value: 2
        },
        {
          label: '未跟进客户',
          value: 3
        }
      ])
      const CascaderData = reactive({
        deptCascaderValue: null,
        customerCascaderValue: '',
      })
      // 部门员工单选
      const getDept = (val) => {
        if (val) {
          msg.EmpId = val.slice(2)
        } else {
          msg.EmpId = 0
        }
        ctx.emit('update')
      }
      const data = reactive({
        isshowlabel: false, //设置标签弹窗
        showTransfer: false, //转移客户弹窗
        showAbandon: false, //放弃客户弹窗
        showImport: false, //导入组件弹窗
        showDptDialog: false, //部门弹窗
        importTab: 1,
        DptDialogArr: [],
        DistributionRule: 1,
      })
      const getlabel = val => {
        const ids = val.map(e => e.Id).toString()
        setLabel(ids)
      }
      const setLabel = (id) => {
        const labelMsg = {
          CustomerIds: props.select.map(e => e.Id).toString(),
          LableIds: id
        }
        customerService.setCustomLabelBatch(labelMsg).then(res => {
          message.successMsg(res.data.Message)
          data.isshowlabel = false
          ctx.emit('update')
        })
      }
      const getFile = (val) => {
        console.log("文件", val)
      }
      //导入是获取部门arr
      const getDeptDig = (arr) => {
        //数据处理 获取id是 1-id,2-id 前面1代表部门2代表人员 后面是原生ID
        console.log('DptDialogArr', arr)
        data.DptDialogArr = arr
      }
      const showDialog = (dialogName) => {
        data[dialogName] = true
      }
      //转移
      const TransferMsg = reactive({
        CustomerIds: '',
        EmpId: 0
      })
      const setTransfer = async () => {
        TransferMsg.CustomerIds = props.select.map(e => e.Id).toString()
        await customerService.setCustomerTransfer(TransferMsg).then(res => {
          message.successMsg(res.data.Message)
          data.showTransfer = false
          ctx.emit('update')
        })
        TransferMsg.EmpId = 0
      }
      //放弃
      const AbandonMsg = reactive({
        CustomerIds: '',
        Reason: ""
      })
      const setAbandon = async () => {
        AbandonMsg.CustomerIds = props.select.map(e => e.Id).toString()
        await customerService.setCustomerAbandon(AbandonMsg).then(res => {
          message.successMsg(res.data.Message)
          data.showAbandon = false
          ctx.emit('update')
        })
        AbandonMsg.Reason = ''

      }
      //彻底删除
      const delCustomer = () => {
        Dialog.create({
          title: '确认删除？',
          message: "请输入'删除'",
          prompt: {
            model: '',
            isValid: val => val == '删除', // << here is the magic
            outlined: true
          },
          cancel: '取消',
          ok: '确认'
        }).onOk(() => {
          const delMsg = {
            CustomerIds: props.select.map(e => e.Id).toString()
          }
          customerService.delCustomerInfo(delMsg).then(res => {
            message.successMsg(res.data.Message)
            ctx.emit('update:select',[])
            ctx.emit('update')
          })
        })
      }
      const closeSel = ()=>{
        ctx.emit('update:select',[])
      }
      return {
        updatePage,
        clearSelectWay,
        zhCN,
        dateZhCN,
        pageCode,
        vtBtn,
        getSelectWay,
        SeletObj,
        TimeObj,
        TypeList,
        TimeList,
        changeTime,
        changeTimeRange,
        getDept,
        CustomList,
        CascaderData,
        ...toRefs(data),
        getlabel,
        getFile,
        getDeptDig,
        showDialog,
        delCustomer,
        setTransfer,
        setAbandon,
        AbandonMsg,
        TransferMsg,
        closeSel,
      }
    }
  }

</script>
