<template>
  <div v-loading="pageLoading" class="app-container">
    <card-table :loading="loading" :modalData="leadList" :searchParams="queryParams" :tableSearch="true"
                labelWidth="120px" @columnSearch="handleQuery" @pagination="getList" @resetList="resetQuery"
                @sortChange="sortChange" @selection-change="handleSelectionChange" :max-height="$store.getters.tableMaxHeight"
                show-no show-selection
    >

      <template #operations="{ selections }">
        <el-button v-hasPermi="['business:lead:add']" icon="el-icon-plus" size="mini" type="primary"
                   @click="handleAdd"
        >{{ $t('lead.addLead') }}
        </el-button>
        <el-button v-hasPermi="['business:lead:allot']" :disabled="multiple" icon="el-icon-edit" size="mini"
                   type="primary" @click="handleAllocate"
        >{{ $t('lead.bulkAllocate') }}
        </el-button>
        <el-button v-hasPermi="['business:lead:convertCust']" :disabled="multiple" icon="el-icon-edit" size="mini"
                   type="primary" @click="handleConvertCust"
        >{{ $t('lead.convertCust') }}
        </el-button>
        <ImportModal v-hasPermi="['business:lead:import']" :close="getList" :tableType="4"
                     :title="$t('common.import')"
                     icon="el-icon-upload2" style="margin: 0 10px;"
        ></ImportModal>
        <el-button v-hasPermi="['business:lead:export']" icon="el-icon-download" plain size="mini"
                   @click="handleExport"
        >{{ $t('lead.export') }}
        </el-button>
      </template>

      <template #default="{ list }">
        <!--<el-table-column align="center" type="selection" width="55"/>-->
        <!--<el-table-column align="center" fixed label="No." type="index" width="50"/>-->
        <!--线索编号-->
        <Column :label="$t('lead.leadNo')" :showSearch="true" fixed prop="leadNo" sortable="custom">
          <template #default="{ row }">
            <span class="link-type" @click="handleView(row)">{{ row.leadNo }}</span>
          </template>
        </Column>
        <!--来源-->
        <Column :label="$t('lead.origin')" :searchDict="dict.type.lead_source" :showSearch="true" prop="origin"
                searchType="select" selectMore
        >
        </Column>
        <!--状态-->
        <Column :label="$t('lead.status')" :searchDict="dict.type.lead_status" :showSearch="true"
                prop="status" searchType="select" selectMore sortable="custom"
        >
          <template #default="{ row }">
            <ColorDictTag :bgc="statusColorMap[row.status].bgc"
                          :label="convertStatus(row.status)"
                          :label-color="statusColorMap[row.status].color"
            />
          </template>
        </Column>
        <!--区域-->
        <Column :label="$t('lead.area')" labelProp="second" :searchDict="areaOps"
                :showSearch="true"
                prop="areaId" searchType="select" selectMore valueProp="first"
        >
          <template #default="{ row }">
            <span>{{ row.areaName }}</span>
            <!--<span>{{ getAgentName(row.areaId) }}</span>-->
          </template>
        </Column>
        <!--国家-->
        <Column :label="$t('lead.country')" :search-dict="curCountryOps" :showSearch="true" label-prop="second"
                prop="countryId"
                search-type="select" select-more value-prop="first"
        >
          <template #default="{ row }">
            <span>{{ row.countryName }}</span>
          </template>
        </Column>

        <!--城市-->
        <Column :label="$t('project.city')" :showSearch="true" prop="city"/>

        <!--负责人-->
        <Column :label="$t('lead.owner')" :showSearch="true" prop="ownerName"/>
        <!--负责代理商-->
        <Column :label="$t('lead.agent')" :search-dict="curAgentOps" :showSearch="true" label-prop="ownerAgentName"
                prop="ownerAgent"
                search-type="select" select-more value-prop="ownerAgent"
        >
          <template #default="{ row }">
            <span>{{ row.ownerAgent === 0 ? $t('agent.headquarters') : row.ownerAgentName }}</span>
          </template>
        </Column>

        <!--客户姓名-->
        <!--<Column :label="$t('lead.customerName')" :showSearch="true" prop="accountName"/>-->

        <!--公司-->
        <Column :label="$t('lead.company')" :showSearch="true" prop="company"/>
        <!--公司类型 companyType-->
        <Column :label="$t('lead.companyType')" :searchDict="dict.type.lead_company_type" :showSearch="true"
                prop="companyType" searchType="select" selectMore
        />

        <!--需求分类 requirementType-->
        <Column :label="$t('lead.requirements')" :searchDict="dict.type.lead_requirements" :showSearch="true"
                prop="requirementType" searchType="select" selectMore
        />

        <!--优先级-->
        <Column :label="$t('lead.priority')" :searchDict="dict.type.lead_priority" :showSearch="true"
                prop="priority" searchType="select" selectMore sortable="custom"
        />

        <!--最新跟进结果-->
        <Column :label="$t('lead.lastestFollowUp')" prop="lastFollowResult" width="250"/>

        <!--最新跟进时间-->
        <!--<Column :label="$t('lead.followUpTime')" prop="lastFollowTime" search-type="dateRange" showSearch sortable="custom"-->
        <!--        width="250">-->
        <!--</Column>-->
        <Column :label="$t('lead.followUpTime')" prop="lastFollowTime" sortable="custom"/>

        <!--跟进人-->
        <Column :label="$t('lead.follower')" prop="follower"/>

        <!--产品意向-->
        <Column :label="$t('lead.intentionalProduct')" :searchDict="dict.type.intentional_product" :showSearch="true"
                prop="intentionalProduct" searchType="select" selectMore
        />

        <!--项目类型-->
        <Column :label="$t('lead.segment')" :searchDict="dict.type.project_type" :showSearch="true" prop="segment"
                searchType="select" selectMore
        />

        <!--创建人-->
        <Column :label="$t('common.createBy')" :showSearch="true" prop="createByNickName"/>

        <!--创建日期-->
        <Column :label="$t('common.createTime')" prop="createTime" search-type="dateRange" showSearch sortable="custom"
                width="250"
        />

        <Column :label="$t('common.operate')" :min-width="250" :showSearch="true" fixed="right"
                searchType="operate"
        >
          <template #default="{ row }">
            <!--<el-button size="mini" type="text" icon="el-icon-edit" v-show="row.followable"
                       @click="handleCommand('handleUpdate', row)" v-hasPermi="['business:lead:edit']">
              {{ $t('common.edit') }}
            </el-button>


            <el-button size="mini" type="text" icon="el-icon-right" v-show="row.followable"
                       @click="handleCommand('handleFollow', row)" v-hasPermi="['business:account:follow']">
              {{ $t('lead.followUp') }}
            </el-button>

            <el-dropdown style="margin-left:5px"
                         v-show=" row.assignable || row.recyclable || row.convertable || row.convertProjectable  || row.silentOrInvalidAble"
                         v-hasPermi="['business:lead:allot', 'business:lead:recycle', 'business:lead:convertCust', 'bussess:lead:convertProjectable', 'business:lead:del', 'business:lead:silentOrInvalid']"
                         size="mini"
                         @command="(command) => handleCommand(command, row)"
            >
              <el-button icon="el-icon-d-arrow-right" size="mini" type="text">{{ $t('common.more') }}</el-button>
              <el-dropdown-menu slot="dropdown">

                <el-dropdown-item v-show="row.assignable" v-hasPermi="['business:lead:allot']" command="handleAllocate"
                                  icon="el-icon-share"
                >{{ $t('lead.allocate') }}
                </el-dropdown-item>
                <el-dropdown-item v-show="row.recyclable" v-hasPermi="['business:lead:recycle']" command="handleRecycle"
                                  icon="el-icon-circle-check"
                >{{ $t('lead.recycle') }}
                </el-dropdown-item>

                <el-dropdown-item v-show="row.convertable" v-hasPermi="['business:lead:convertCust']"
                                  command="handleConvertCust"
                                  icon="el-icon-check"
                >{{ $t('lead.convertCust') }}
                </el-dropdown-item>
                <el-dropdown-item v-show="row.convertProjectable" v-hasPermi="['bussess:lead:convertProjectable']"
                                  command="handleConvertProject"
                                  icon="el-icon-check"
                >{{ $t('lead.convertProject') }}
                </el-dropdown-item>
                <el-dropdown-item v-show="row.deletable" v-hasPermi="['business:lead:del']" command="handleDelete"
                                  icon="el-icon-delete"
                >{{ $t('common.delete') }}
                </el-dropdown-item>
                <el-dropdown-item v-show="row.silentOrInvalidAble" v-hasPermi="['business:lead:silentOrInvalid']"
                                  command="handleSilentOrInvalid"
                                  icon="el-icon-remove-outline"
                >{{ $t('lead.silentOrInvalid') }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>-->


            <MoreBtn :handle-command="handleCommand" :row="row" :btns="[
              { label: $t('common.edit'), icon: 'el-icon-edit', command: 'handleUpdate', permi: 'business:lead:edit', showAble: row.followable },
              { label: $t('lead.followUp'), icon: 'el-icon-right', command: 'handleFollow', permi: 'business:account:follow', showAble: row.followable },
              { label: $t('lead.allocate'), icon: 'el-icon-share', command: 'handleAllocate', permi: 'business:lead:allot', showAble: row.assignable },
              { label: $t('lead.recycle'), icon: 'el-icon-circle-check', command: 'handleRecycle', permi: 'business:lead:recycle', showAble: row.recyclable },
              { label: $t('lead.convertCust'), icon: 'el-icon-check', command: 'handleConvertCust', permi: 'business:lead:convertCust', showAble: row.convertable },
              { label: $t('lead.convertProject'), icon: 'el-icon-check', command: 'handleConvertProject', permi: 'bussess:lead:convertProjectable', showAble: row.convertProjectable },
              { label: $t('common.delete'), icon: 'el-icon-delete', command: 'handleDelete', permi: 'business:lead:del', showAble: row.deletable },
              { label: $t('lead.silentOrInvalid'), icon: 'el-icon-remove-outline', command: 'handleSilentOrInvalid', permi: 'business:lead:silentOrInvalid', showAble: row.silentOrInvalidAble }
            ]"/>

          </template>

        </Column>
      </template>
    </card-table>

    <!-- 添加或修改【线索】对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" append-to-body
               custom-class="edit-dialog" top="5%"
               width="50vw"
    >
      <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="150px">
        <!--优先级-->
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item :label="$t('lead.priority')" prop="priority">
              <el-radio-group v-model="form.priority">
                <el-radio v-for="item in dict.type.lead_priority" :key="item.value" :label="item.value">{{
                    item.label
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!--区域、国家-->
        <el-row :gutter="24">
          <el-col :span="12">
            <!-- 区域 -->
            <el-form-item :label="$t('user.area')" prop="areaId">
              <!-- 加 :flat="true" 是为了根节点设置 isDisabled 禁用时， 子节点可选-->
              <treeselect v-model="form.areaId" :flat="true" :options="areaTree" :noResultsText="$t('common.noResultsText')"
                          :placeholder="$t('user.placeholder_area')"
                          :show-count="true" class="w-100"
                          @input="clearArea" @select="areaChange"
              >
                <!--TODO 直接使用 localLabel-->
                <div slot="option-label" slot-scope="{ node }" style="white-space: nowrap; font-size: 14px">
                  {{ node.raw['label' + localLabelSuffix] ? node.raw['label' + localLabelSuffix] : '' }}
                </div>
                <div slot="value-label" slot-scope="{ node }">
                  {{ node.raw['label' + localLabelSuffix] ? node.raw['label' + localLabelSuffix] : '' }}
                </div>
              </treeselect>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <Select v-model="form.countryId" :data="countryOptions" :label="$t('lead.country')"
                    :label-prop="'countryName' + localLabelSuffix"
                    prop="countryId" required value-prop="countryId" width="100%"
            />
          </el-col>
        </el-row>

        <!-- 城市、需求类型-->
        <el-row :gutter="24">
          <!--          城市-->
          <el-col :span="12">
            <Input v-model="form.city" :label="$t('project.city')" :maxlength="100" prop="city"
                   property="city" width="100%" required
            />
          </el-col>

          <!--需求类型-->
          <el-col :span="12">
            <Select v-model="form.requirementType" :data="dict.type.lead_requirements" :label="$t('lead.requirements')"
                    prop="requirementType" required width="100%"
            />
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <!--公司名称-->
          <el-col :span="12">
            <Input v-model="form.company" :label="$t('lead.company')" :maxlength="100" prop="company"
                   required width="100%"
            />
          </el-col>

          <!--公司类型-->
          <el-col :span="12">
            <Select v-model="form.companyType" :data="dict.type.lead_company_type" :label="$t('lead.companyType')"
                    required prop="companyType" width="100%"
            />
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <!--归属集团-->
          <el-col :span="12">
            <Input v-model="form.group" :label="$t('lead.group')" :maxlength="255" prop="group"
                   width="100%"
            />
          </el-col>

          <!--公司背景-->
          <el-col :span="12">
            <Input v-model="form.background" :label="$t('lead.background')" :maxlength="255" prop="background"
                   width="100%"
            />
          </el-col>
        </el-row>


        <el-row :gutter="24">
          <!--来源-->
          <el-col v-if="!$store.state.user.userInfo.deptId !== 0 || $store.state.user.userInfo.areaId !== 0" :span="12">
            <Select v-model="form.origin" :data="dict.type.lead_source"
                    :label="$t('lead.origin')" prop="origin" required width="100%"
            />
          </el-col>

          <!-- 项目类型 -->
          <el-col :span="12">
            <Select v-model="form.segment" :data="dict.type.project_type" :label="$t('lead.segment')" prop="segment"
                    width="100%"
            />
          </el-col>
        </el-row>

        <!--2024-0621客户指摘-->
        <!--<el-row :gutter="24">-->
        <!--  &lt;!&ndash;客户名称&ndash;&gt;-->
        <!--  <el-col :span="12">-->
        <!--    <Input v-model.trim="form.accountName" :label="$t('lead.customerName')" :maxlength="100" prop="accountName"-->
        <!--           required width="100%"-->
        <!--    />-->
        <!--  </el-col>-->
        <!--  &lt;!&ndash;客户类型&ndash;&gt;-->
        <!--  <el-col :span="12">-->
        <!--    <Select v-model="form.type" :data="dict.type.account_type" :label="$t('lead.leadCustomerType')" prop="type"-->
        <!--            required width="100%"-->
        <!--    />-->
        <!--  </el-col>-->
        <!--</el-row>-->

        <el-row :gutter="24">
          <!--联系人-->
          <el-col :span="12">
            <Input v-model.trim="form.contactPerson" :label="$t('common.contactPerson')" :maxlength="100"
                   prop="contactPerson"
                   required width="100%"
            />
          </el-col>
          <!--联系方式-->
          <el-col :span="12">
            <Input v-model.trim="form.contact" :label="$t('common.contact')" :maxlength="100" :rules="rules.contact"
                   prop="contact" width="100%"
            />
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <!--邮箱-->
          <el-col :span="12">
            <Input v-model="form.email" :label="$t('lead.email')" :maxlength="50" :rules="rules.email"
                   prop="email" type="email" width="100%"
            />
          </el-col>


          <!--职位-->
          <el-col :span="12">
            <Input v-model="form.jobTitle" :label="$t('lead.position')" :maxlength="255" prop="jobTitle"
                   property="jobTitle" width="100%"
            />
          </el-col>
        </el-row>


        <el-row :gutter="24">
          <el-col :span="12">
            <!--产品意向-->
            <Select v-model="form.intentionalProduct" :data="dict.type.intentional_product"
                    :label="$t('lead.intentionalProduct')" prop="intentionalProduct" width="100%"
            />
          </el-col>
        </el-row>

        <!--询盘信息-->
        <Input v-model="form.requirement" :label="$t('lead.inquiryInformation')" :maxlength="3000" prop="requirement"
               required type="textarea" width="100%"
        />


        <!--地址-->
        <el-row>
          <el-col :span="24">
            <Input v-model.trim="form.address" :label="$t('lead.address')" :maxlength="100" prop="address"
                   width="100%"
            />
          </el-col>
        </el-row>

        <!--备注-->
        <el-row>
          <el-col :span="24">
            <Input v-model.trim="form.remark" :label="$t('common.remark')" :maxlength="500" prop="remark"
                   type="textarea"
                   width="100%"
            />
          </el-col>
        </el-row>

        <!--附件-->
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('common.annex')">
              <FileUpload v-model="form.annex" :buttonText="$t('common.uploadFile')" :class="{ 'upload': false }"
                          :disabled="false" :fileType="[]" :isShowTip="false" :fileSize="50"
              >
              </FileUpload>

            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-circle-check" type="primary" @click="submitForm">{{ $t('common.confirm') }}</el-button>
        <el-button icon="el-icon-remove-outline" @click="cancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>

    <!-- 分配-->
    <el-dialog :close-on-click-modal="false" :title="alloctBatch ? $t('lead.bulkAllocate') : $t('lead.allocate')"
               :visible.sync="allocateOpen" append-to-body top="5%" width="500px"
    >
      <el-form ref="allocateForm" :model="allocateForm" :rules="allotRules" label-position="top" label-width="100px">

        <!--线索编号-->
        <el-row v-if="!alloctBatch">
          <el-col :span="24">
            <el-form-item :label="$t('lead.no')">
              <el-input v-model="allocateForm.leadNo" :placeholder="$t('common.pleaseInput') + $t('lead.no')"
                        class="w-100"
                        readonly
              />
              <!--<el-tooltip class="item" :content="allocateForm.leadNo" placement="top" v-if="allocateForm.leadNo.length > 20">-->
              <!--</el-tooltip>-->
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 下拉框 -->
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('lead.owner')" prop="owner">
              <el-select v-model="allocateForm.owner" :placeholder="$t('common.pleaseSelect') + $t('lead.owner')"
                         class="w-100" clearable filterable
              >
                <el-option v-for="item in nextLevels" :key="item.userId" :label="item.nickName"
                           :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-circle-check" type="primary" @click="submitAllocate">{{
            $t('common.confirm')
          }}
        </el-button>
        <el-button icon="el-icon-remove-outline" @click="cancelAllocate">{{ $t('common.cancel') }}</el-button>
      </div>

    </el-dialog>

    <!-- 回收 -->
    <el-dialog :close-on-click-modal="false" :title="$t('lead.recycleLead')" :visible.sync="recycleOpen" append-to-body
               top="5%"
               width="40vw"
    >
      <el-form ref="recycleForm" :model="recycleForm" :rules="recycleRules" label-position="top" label-width="8vw">

        <!--线索编号-->
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('lead.no')">
              <el-input v-model="recycleForm.leadNo" :placeholder="$t('common.pleaseSelect') + $t('lead.owner')"
                        class="w-100" readonly
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 下拉框 -->
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('lead.recoveryType')" prop="recoveryType">
              <el-select v-model="recycleForm.recoveryType"
                         :placeholder="$t('common.pleaseSelect') + $t('lead.recoveryType')"
                         class="w-100" clearable
              >
                <el-option v-for="item in dict.type.reason_type" :key="item.value" :label="item.label"
                           :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!--回收原因-->
        <el-row>
          <el-col :span="24">
            <el-form-item :label="$t('lead.recoveryReason')">
              <el-input v-model="recycleForm.recoveryReason"
                        :maxlength="500"
                        :placeholder="$t('common.pleaseInput') + $t('lead.recoveryReason')" show-word-limit
                        type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-circle-check" type="primary" @click="submitRecycle">{{
            $t('common.confirm')
          }}
        </el-button>
        <el-button icon="el-icon-remove-outline" @click="cancelRecycle">{{ $t('common.cancel') }}</el-button>
      </div>

    </el-dialog>

    <!-- 跟进 -->
    <FollowDialog ref="followDialog" @returnRow="getList"/>

    <!--转化项目-->
    <ProjectDialog ref="projectForm" :form="convertProjectForm"
                   :title="$t('project.addProject')" :visible="projectOpen"
                   @closeDialog="closeConvertProjectDialog"
    >
    </ProjectDialog>

    <!-- 转化客户 -->
    <el-dialog :close-on-click-modal="false" :title="$t('lead.convertCustTitle')"
               :visible.sync="convertCustOpen" append-to-body top="5%" width="30vw"
    >
      <el-form ref="convertCustForm" :model="convertCustForm" label-position="top" label-width="100px">

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item :label="$t('lead.convertCustType')" required>

              <el-radio-group v-model="isNewCustomer">
                <el-radio :label="1">{{ $t('lead.convertNewCustomer') }}</el-radio>
                <el-radio :label="0">{{ $t('lead.convertExistCust') }}</el-radio>
              </el-radio-group>

              <!--<el-radio v-model="isNewCustomer" :label="1">{{ $t('lead.convertNewCustomer') }}</el-radio>-->
              <!--<el-radio v-model="isNewCustomer" :label="0">{{ $t('lead.convertExistCust') }}</el-radio>-->
            </el-form-item>
          </el-col>

        </el-row>
        <PageSelect v-if="convertCustOpen && !isNewCustomer" :defaultData="[]" :formatLabel="formatLabel"
                    :label="$t('project.relatedCustomer')"
                    :list="listRemotePage" :pageSize="10" :placeholder="$t('common.pleaseSelect') + $t('project.relatedCustomer')"
                    :visibleGetData="true" class="account-select" clearable idName="accountId" labelProp="accountNo"
                    prop="accountId"
                    required valueProp="accountId"
                    width="100%" @change="changeAccountPage"
        />
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-circle-check" type="primary" @click="submitConvertCust">{{
            $t('common.confirm')
          }}
        </el-button>
        <el-button icon="el-icon-remove-outline" @click="cancelConvert">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>


    <!--静默、无效-->
    <el-dialog :close-on-click-modal="false" :title="$t('lead.silentOrInvalid')"
               :visible.sync="silentOrInvalidOpen" append-to-body top="5%" width="30vw"
    >

      <el-form ref="silentOrInvalidForm" :model="silentOrInvalidForm" label-position="top" label-width="100px">

        <el-form-item :label="$t('lead.silentOrInvalid')" required prop="status">
          <!-- 8： 无效； 10：静默-->
          <el-radio v-for="item in dict.type.lead_status.filter(item => ['8', '10'].includes(item.value))"
                    :key="item.value"
                    v-model="silentOrInvalidForm.status"
                    :label="item.value"
          >{{ item.label }}
          </el-radio>
        </el-form-item>

        <Input :label="$t('common.remark')" :maxlength="500" prop="remark"
               type="textarea"
               width="100%"
        />
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-circle-check" type="primary" @click="submitSilentOrInvalid">{{
            $t('common.confirm')
          }}
        </el-button>
        <el-button icon="el-icon-remove-outline" @click="cancelSilentOrInvalid">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import ImageUpload from '@/components/ImageUpload/index.vue'
import {
  addLead,
  allot,
  convertCust,
  curAgent,
  delLead,
  getAreaList,
  getCountryList,
  getLead,
  getNextLevelsByCur,
  listLead,
  recycle, silentInvalid,
  updateLead
} from '@/api/business/crm/lead'
import DictSelect from '@/components/element/form/items/DictSelect.vue'
import Column from '@/components/element/table/Column.vue'
import ColorDictTag from '@/views/crmManagement/lead/ColorDictTag/index.vue'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {getAreaTreeByUser} from '@/api/common/common'
import {getCountryByAreaId} from '@/api/system/user'
import {getLocalTime} from '@/utils/data/dataUtils'
import FollowDialog from '@/views/crmManagement/follow/FollowDialog.vue'
import ImportModal from '@/components/ImportModal/index.vue'
import {parseTime} from '@/utils/ruoyi'
import ProjectDialog from '@/views/crmManagement/project/dialog.vue'
import FileUpload from '@/components/FileUpload'
import PageSelect from '@/components/element/form/items/PageSelect.vue'
import {listRemotePage} from '@/api/business/crm/account'
import MoreBtn from '@/components/MoreBtn/index.vue'
import { getAgent } from '@/api/user/agent'

const statusColorMap = {
  1: {
    color: '#FFC500',
    bgc: 'rgba(255,200,12,0.12)'
  },
  2: {
    color: '#24CA5D',
    bgc: 'rgba(24,199,84,0.12)'
  },
  3: {
    color: '#8B71FD',
    bgc: 'rgba(139,113,253,0.12)'
  },
  4: {
    color: '#0DCCD7',
    bgc: 'rgba(13,204,215,0.12)'
  },
  5: {
    color: '#218AFC',
    bgc: '#E5F1FF'
  },
  6: {
    color: '#FC5821',
    bgc: 'rgba(252,88,33,0.12)'
  },
  7: {
    color: '#FC5821',
    bgc: 'rgba(252,88,33,0.12)'
  },
  8: {
    color: '#AD2BBF',
    bgc: 'rgba(163,32,181,0.12)'
  },
  9: {
    color: '#0B8B21',
    bgc: 'rgba(11,139,33,0.12)'
  },
  10: {
    color: '#D71943',
    bgc: '#FAEDED'
  },
  undefined: {
    color: '#D71943',
    bgc: '#FAEDED'
  },
  null: {
    color: '#D71943',
    bgc: '#FAEDED'
  }
}

export default {
  name: 'Lead',
  components: {
    MoreBtn,
    PageSelect,
    ProjectDialog,
    ImportModal,
    FollowDialog,
    Treeselect,
    ImageUpload,
    ColorDictTag,
    Column,
    DictSelect,
    FileUpload
  },
  dicts: ['lead_priority', 'lead_status', 'lead_source', 'account_type', 'lead_industry', 'reason_type'
    , 'company_type', 'project_type', 'lead_requirements', 'intentional_product', 'lead_company_type'],
  data() {
    return {
      // 遮罩层
      loading: false,
      pageLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      leadList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      allocateOpen: false,
      recycleOpen: false,
      // 是否可编辑
      // editable: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        leadNo: null,
        countryId: null,
        areaId: null,
        origin: null,
        contactPerson: null,
        contact: null,
        email: null,
        sector: null,
        address: null,
        company: null,
        requirement: null,
        priority: null,
        status: null,
        owner: null,
        leadTime: null,
        type: null,
        relativeAccount: null,
        relativeProject: null,
        relativeContract: null,
        unvalidReason: null,
        createByName: null
      },
      // 表单参数
      form: {},
      validateContact: true,
      validateEmail: true,
      // 表单校验
      rules: {
        // 区域
        areaId: [
          {required: true, message: this.$t('common.pleaseSelect') + ' ' + this.$t('user.area'), trigger: 'change'}
        ],
        // 优先级
        priority: [
          {required: true, message: this.$t('common.pleaseSelect') + this.$t('lead.priority'), trigger: 'change'}
        ],
        // 联系方式
        contact: [
          // {required: true, message: this.$t('common.pleaseInput') + this.$t('common.contact'), trigger: 'blur'},
          // 至少5位数
          {min: 5, message: this.$t('common.atLeast') + 5 + this.$t('common.digits'), trigger: 'blur'},
          // 联系方式和邮箱至少输入一个
          {
            validator: (rule, value, callback) => {
              if (!value) {
                this.validateContact = true
                this.validateEmail = true
              }
              if (!value && !this.form.email && this.validateContact) {
                callback(new Error(this.$t('lead.contactOrEmailRequired')))
              } else {
                // 触发 email 校验
                if (this.validateContact) {
                  this.validateEmail = false
                  // 最简单的办法是 清除校验
                  this.$refs.form.validateField('email')
                }
                callback()
              }
            }, trigger: 'blur'
          }

        ],
        email: [
          {type: 'email', message: this.$t('common.pleaseCorrect') + this.$t('agent.email'), trigger: 'blur'},
          // 联系方式和邮箱至少输入一个
          {
            validator: (rule, value, callback) => {
              if (!value) {
                this.validateContact = true
                this.validateEmail = true
              }
              if (!value && !this.form.contact && this.validateEmail) {
                callback(new Error(this.$t('lead.contactOrEmailRequired')))
              } else {
                // 触发 contact 校验
                if (this.validateEmail) {
                  this.validateContact = false
                  this.$refs.form.validateField('contact')
                }
                callback()
              }
            }, trigger: 'blur'
          }
        ]

      },
      statusColorMap: statusColorMap,

      // 地区下拉
      areaOps: [],
      // 快速查询
      areaMap: new Map(),
      // 国家下拉：
      countryOptions: [],
      // 地区树
      areaTree: [],
      // 当前用户全部线索列表中的代理商 下拉
      curAgentOps: [],
      // 当前用户全部线索列表中的国家 下拉
      curCountryOps: [],

      //
      limitPic: 5,

      nextLevels: {},

      alloctBatch: false,
      allocateForm: {
        // leadId: null,
        // leadIds: null,
        leadNo: null,
        owner: null
        // ownerAgent: null,
        // updateTime: null,
      },
      allocates: [],
      // 下级用户层级：   AREA("区域"), AGENT("代理商")
      nextLevelType: null,
      allotRules: {
        owner: [
          {required: true, message: this.$t('common.pleaseSelect') + this.$t('lead.owner'), trigger: 'change'}
        ]
      },

      recycleForm: {
        actionType: '2',
        leadId: null,
        leadNo: null,
        owner: null,
        recoveryType: null,
        recoveryReason: null,
        updateTime: null
      },
      recycleRules: {
        recoveryType: [
          {required: true, message: this.$t('common.pleaseSelect') + this.$t('lead.recoveryType'), trigger: 'change'}
        ],
        recoveryReason: [
          // {required: true, message: '请输入回收原因', trigger: 'blur'}
        ]
      },

      // 专户项目 dialog
      projectOpen: false,
      convertProjectForm: {},

      convertCustOpen: false,
      convertCustForm: {
        leadIds: [],
        updateTime: null
        // relativeAccount: null,
      },
      isNewCustomer: 1,

      silentOrInvalidOpen: false,
      silentOrInvalidForm: {
        // leadIds: [],
        leadId: null,
        updateTime: null,
        remark: null,
      }

    }
  },
  created() {
    this.getList()
    // this.getAreaOps()
    // this.getAreaTree();
    this.curAgent()
    // this.curCountry()

    this.listenRefreshListVuex()
  },

  mounted() {
  },

  computed: {
    localLabelSuffix() {
      return localStorage.getItem('labelSuffix') || ''
    }
  },

  watch: {

    //   form.annex
    'form.annex': {
      handler(val) {
        // console.log('val', val)
      },
      deep: true
    }
  },

  methods: {
    listRemotePage,

    formatLabel(accountNo, item) {
      return item.accountNo + ': 【' + item.accountName + '】'
    },

    changeAccountPage(row) {
    },

    translateDict(value, type) {
      if (!value) return '-'
      // return this.dict.type[type].filter(item => item.value === value)[0].label
    },

    listenRefreshListVuex() {
      this.$store.subscribe((mutation) => {
        if (mutation.type === 'refreshLead') {
          this.getList()
        }
      })
    },

    resetList() {
    },
    getLocalTime,
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true

      listLead(this.queryParams).then(response => {
        this.leadList = response.rows
        // this.total = response.total;
        this.queryParams.total = response.total
        this.loading = false
      })

      this.getAreaOps()
      this.curCountry()
    },

    async getAreaOps() {
      const response = await getAreaList()
      this.areaOps = response.data
      // this.areaMap = response.data.reduce((map, obj) => {
      //   map.set(obj.areaId, obj)
      //   return map
      // }, new Map())
    },

    // 获取地区树
    async getAreaTree() {
      const response = await getAreaTreeByUser()
      this.areaTree = response.data || []
      console.log('allAreaList', this.areaTree)
      // 如果存在全球根节点（id=0），则排除根节点
      if (this.areaTree.some(item => item.id === 0)) {
        this.areaTree = this.areaTree.filter(item => item.id !== 0)
      }

      // 如果只有一个区域：列表中只有一个且没有子节点，则直接选中
      if (this.areaTree.length === 1 && (!this.areaTree[0].children || this.areaTree[0].children?.length === 0)) {
        this.form.areaId = this.areaTree[0].id
        await this.getCountryByAreaId(this.areaTree[0].id)
      }

    },

    async areaChange(val) {
      // console.log('val', val)
      this.$set(this.form, 'countryId', '')
      if (val.id) {
        await this.getCountryByAreaId(val.id)
      }
    },

    clearArea(val) {
      if (!val) {
        this.$set(this.form, 'countryId', '')
      }
      // 出发本身校验
      this.$refs.form.validateField('areaId')
      this.countryOptions = []
    },

    async getCountryByAreaId(areaId) {
      const agentId = this.$store.getters.agentId;
      if (agentId <= 0) {
        const resp = await getCountryByAreaId(areaId)
        this.countryOptions = resp.data
      } else {
        const response = await getAgent(agentId)
        this.countryOptions = response.data?.countryList || []
      }
      // 如果只有一个国家，就直接选中
      if (this.countryOptions.length === 1) {
        this.form.countryId = this.countryOptions[0].countryId
      }
      // console.log('nationList', this.countryOptions)
    },

    convertStatus(status) {
      if (!status) return '-'
      return this.dict.type.lead_status.filter(item => item.value === status)[0].label
    },

    async curAgent() {
      const response = await curAgent()
      this.curAgentOps = response.data
      // 如果存在 ownerAgent =0，则添加总部选项
      // if (this.curAgentOps.some(item => item.ownerAgent === 0)) {
      this.curAgentOps.unshift({ownerAgent: 0, ownerAgentName: this.$t('agent.headquarters')})
      // }
    },
    async curCountry() {
      const response = await getCountryList()
      this.curCountryOps = response.data
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'handleUpdate':
          this.handleUpdate(row)
          break
        case 'handleAllocate':
          this.handleAllocate(row)
          break
        case 'handleRecycle':
          this.handleRecycle(row)
          break
        case 'handleFollow':
          this.handleFollow(row)
          break
        case 'handleConvertCust':
          this.handleConvertCust(row)
          break
        case 'handleConvertProject':
          this.handleConvertProject(row)
          break
        case 'handleDelete':
          this.handleDelete(row)
          break
        case 'handleSilentOrInvalid':
          this.handleSilentOrInvalid(row)
          break
        default:
          break
      }
    },

    // 表单重置
    reset() {
      this.form = {
        leadId: null,
        leadNo: null,
        countryId: null,
        areaId: null,
        origin: null,
        contactPerson: null,
        contact: null,
        email: null,
        sector: null,
        address: null,
        company: null,
        requirement: null,
        priority: null,
        status: null,
        owner: null,
        leadTime: null,
        type: null,
        relativeAccount: null,
        relativeProject: null,
        relativeContract: null,
        unvalidReason: null,
        delFlag: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
        createByName: null
      }
      this.resetForm('form')
      this.countryOptions = []
      this.areaTree = []
    },

    resetAllocate() {
      this.allocateForm = {
        // leadId: null,
        leadNo: null,
        owner: null
        // ownerAgent: null,
        // updateTime: null,
      }
      this.nextLevelType = null

      this.resetForm('allocateForm')
    },

    resetRecycle() {
      this.recycleForm = {
        actionType: '2',
        leadId: null,
        leadNo: null,
        owner: null,
        recoveryType: null,
        recoveryReason: null,
        updateTime: null
      }

      this.resetForm('recycleForm')
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.$set(this.queryParams, "pageNum", 1);
      // this.$set(this.queryParams, "pageSize", 10);
      this.$set(this.queryParams, 'leadNo', null)
      this.$set(this.queryParams, 'accountNo', null)
      this.$set(this.queryParams, 'countryId', null)
      this.$set(this.queryParams, 'areaId', null)
      this.$set(this.queryParams, 'origin', null)
      this.$set(this.queryParams, 'contactPerson', null)
      this.$set(this.queryParams, 'contact', null)
      this.$set(this.queryParams, 'email', null)
      this.$set(this.queryParams, 'sector', null)
      this.$set(this.queryParams, 'address', null)
      this.$set(this.queryParams, 'company', null)
      this.$set(this.queryParams, 'requirement', null)
      this.$set(this.queryParams, 'priority', null)
      this.$set(this.queryParams, 'status', null)
      this.$set(this.queryParams, 'owner', null)
      this.$set(this.queryParams, 'leadTime', null)
      this.$set(this.queryParams, 'type', null)
      this.$set(this.queryParams, 'relativeAccount', null)
      this.$set(this.queryParams, 'relativeProject', null)
      this.$set(this.queryParams, 'relativeContract', null)
      this.$set(this.queryParams, 'unvalidReason', null)
      this.$set(this.queryParams, 'ownerName', null)
      this.queryParams.ownerAgent = null
      this.queryParams.createByName = null
      this.$set(this.queryParams, 'companyType', null)
      this.$set(this.queryParams, 'requirementType', null)
      this.$set(this.queryParams, 'lastFollowResult', null)
      this.$set(this.queryParams, 'follower', null)
      this.$set(this.queryParams, 'intentionalProduct', null)
      this.$set(this.queryParams, 'segment', null)
      this.$set(this.queryParams, 'accountName', null)
      this.$set(this.queryParams, 'countryName', null)
      this.$set(this.queryParams, 'createByNickName', null)
      this.$set(this.queryParams, 'beginTime', null)
      this.$set(this.queryParams, 'endTime', null)
      this.$set(this.queryParams, 'createTime', null)
      this.$set(this.queryParams, 'city', null)
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.leadId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    sortChange({column, prop, order}) {
      if (order === 'ascending') {
        this.queryParams.orderByColumn = prop
        this.queryParams.isAsc = 'asc'
      } else if (order === 'descending') {
        this.queryParams.orderByColumn = prop
        this.queryParams.isAsc = 'desc'
      } else {
        this.queryParams.orderByColumn = null
        this.queryParams.isAsc = null
      }
      this.getList()
    },

    /**  查看按钮操作 */
    handleView(row) {
      this.$tab.openPage(this.$t('lead.detail'), '/crmManagement/lead-view/index/' + row.leadId)
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset()
      // this.editable = true;
      this.form.priority = '1'
      this.title = this.$t('common.add') + this.$t('lead.lead')
      await this.getAreaTree()
      this.open = true

    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.pageLoading = true
      try {
        this.reset()
        const leadId = row.leadId || this.ids
        this.getAreaTree()
        const response = await getLead(leadId)
        // 查询国家
        if (response.data.areaId) {
          this.getCountryByAreaId(response.data.areaId)
        }

        this.form = response.data
        this.open = true
        this.title = this.$t('common.edit') + this.$t('lead.lead')
      } finally {
        this.pageLoading = false
      }
    },

    /** 分配按钮操作 */
    async handleAllocate(row) {
      this.resetAllocate()
      this.allocates = []
      try {
        if (row.leadId) {
          const {leadId, leadNo, updateTime} = row
          this.allocateForm.leadNo = leadNo

          // 取 updateTime 是为了并发排他注解工作
          const lead = {leadId, updateTime, leadNo}
          this.allocates.push(lead)
          this.alloctBatch = false
        } else {
          // 检查每个行是否允许
          for (let id of this.ids) {
            const lead = this.leadList.find(lead => lead.leadId === id)
            if (!lead.assignable) {
              this.$modal.msgError(this.$t('lead.leadNo') + lead.leadNo + this.$t('lead.noAllowed'))
              return
            }
            const {leadId, updateTime, leadNo} = lead
            this.allocates.push({leadId, updateTime, leadNo})
          }
          this.allocateForm.leadNo = this.allocates.map(item => item.leadNo).join(',')
          console.log('this.allocateForm.leadNo', this.allocateForm.leadNo)
          this.alloctBatch = true
        }
        const response = await getNextLevelsByCur()
        //   AREA("区域"), AGENT("代理商")
        // this.nextLevelType = response.data?.nextLevel
        // this.nextLevels = response.data?.nextLevelUsers;
        this.nextLevels = response.data
        this.allocateOpen = true
      } catch (e) {
        console.log('e', e)
        this.allocateOpen = false
      }
    },

    submitAllocate() {
      this.$refs['allocateForm'].validate(valid => {
        if (valid) {
          if (this.allocates && this.allocates.length > 0) {
            // 如果是代理商： 还需保存 ownerAgent
            // let ownerAgent = null;
            // if (this.nextLevelType === 'AGENT') {
            //   ownerAgent = this.nextLevels.find(item => item.userId === this.allocateForm.owner).deptId;
            // }

            for (let allocate of this.allocates) {
              allocate.owner = this.allocateForm.owner
              // allocate.ownerAgent = ownerAgent;
            }
            allot(this.allocates).then(response => {
              this.$modal.msgSuccess(this.$t('lead.allocateSuccess'))
              this.allocateOpen = false
              this.getList()
            })
          }
        }
      })
    },

    cancelAllocate() {
      this.allocateOpen = false
      this.resetAllocate()
    },

    // 回收
    handleRecycle(row) {
      this.resetRecycle()
      const {leadId, leadNo, owner, updateTime} = row
      this.recycleForm.leadId = leadId
      this.recycleForm.leadNo = leadNo
      this.recycleForm.owner = owner
      this.recycleForm.updateTime = updateTime
      // this.recycleForm = { leadId, leadNo, owner, updateTime };
      this.recycleOpen = true
    },

    // TODO loading
    submitRecycle() {
      this.$refs['recycleForm'].validate(valid => {
        if (valid) {
          if (this.recycleForm.leadId) {

            recycle(this.recycleForm).then(response => {
              this.$modal.msgSuccess(this.$t('lead.recycleSuccess'))
              this.recycleOpen = false
              this.getList()
            })
          }
        }
      })
    },

    cancelRecycle() {
      this.recycleOpen = false
      this.resetRecycle()
    },

    /** 提交按钮 */
    submitForm() {
      // this.form.email = this.form.email && this.form.email.length > 0 ? this.form.email : null
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.leadId != null) {
            this.pageLoading = true
            updateLead(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.editSuccess'))
              this.open = false
              this.pageLoading = false
              this.reset()
              this.getList()
            })
          } else {
            addLead(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.addSuccess'))
              this.open = false
              this.pageLoading = false
              this.reset()
              this.getList()
            })
          }
        }
      })
    },

    handleFollow(row) {
      // this.open = true
      // this.$refs.followDialog.dialogItemInit('1', null, row.leadId)
      this.$refs.followDialog.dialogItemInit({flag: '1', leadId: row.leadId})
    },

    // 转化为客户
    handleConvertCust(row) {
      const leadIds = row?.leadId ? [row.leadId] : this.ids
      if (!this.multiple) {
        // 多选是校验：已经转化的不能再转化
        for (let id of this.ids) {
          const lead = this.leadList.find(lead => lead.leadId === id)
          if (lead.status === '5') {
            this.$modal.msgError(this.$t('lead.leadNo') + '【' + lead.leadNo + '】' + this.$t('lead.converted'))
            return
          } else if (!lead.convertable) {
            this.$modal.msgError(this.$t('lead.leadNo') + '【' + lead.leadNo + '】' + this.$t('lead.cannotConvert'))
            return
          }

        }
      }

      // 打开转化客户弹窗（新客户、现有客户）

      // 默认新客户
      this.isNewCustomer = 1
      //
      this.convertCustForm = {
        leadIds: leadIds,
        updateTime: row.updateTime
      }
      this.convertCustOpen = true
      this.resetForm('convertCustForm')

      // this.$tab.openPage(this.$t('account.add'), '/account-edit/index/' + 0, {
      //   type: 'add',
      //   leadIds: leadIds,
      // });
    },

    // 转化项目
    handleConvertProject(row) {
      this.convertProjectForm = {
        leadIds: [row.leadId],
        accountId: row.relativeAccount,
        accountNo: row.relationAccountNo,
        accountName: row.relationAccountName,
        areaId: row.relationAccountAreaId,
        countryId: row.relationAccountCountryId,
        owner: this.$store.getters.userId == 1 ? null : this.$store.getters.userId,
        ownerAgent: row.relationAccountAgentId,
      }

      this.convertProjectForm.accountId = row.relativeAccount + ''
      this.$refs.projectForm.defaultData = [{
        accountId: row.relativeAccount,
        accountNo: row.relationAccountNo,
        accountName: row.relationAccountName,
      }]

      this.$refs.projectForm.myLeadList = [row]

      console.log('this.convertProjectForm', this.convertProjectForm)
      this.projectOpen = true

      this.$refs.projectForm.getRelatedContact(this.convertProjectForm.accountId);
    },

    // 关闭转化项目弹窗
    closeConvertProjectDialog() {
      this.projectOpen = false
      this.convertProjectForm = {}
      this.getList()
    },

    /** 删除按钮操作 */
    async handleDelete(row) {
      try {
        const leadIds = row.leadId || this.ids
        await this.$modal.confirm(this.$t('common.isDelete'))
        this.pageLoading = true
        await delLead(leadIds)
        this.getList()
        this.$modal.msgSuccess(this.$t('common.deleteSuccess'))
      } finally {
        this.pageLoading = false
      }
    },

    // 静默、无效
    handleSilentOrInvalid(row) {
      this.silentOrInvalidForm = {
        // leadIds: row.leadId ? [row.leadId] : this.ids,
        leadId: row.leadId,
        updateTime: row.updateTime,
        status: '8',
        remark: null
      }
      this.silentOrInvalidOpen = true
    },

    submitSilentOrInvalid() {
      this.$refs['silentOrInvalidForm'].validate(async valid => {
        if (valid) {
          this.pageLoading = true
          try {
            if (this.silentOrInvalidForm.leadId) {
              await silentInvalid(this.silentOrInvalidForm)
            }
            this.getList()
          } catch (error) {
            console.error(error)
          } finally {
            this.pageLoading = false
          }
          this.silentOrInvalidOpen = false
        }
      })
    },

    cancelSilentOrInvalid() {
      this.silentOrInvalidOpen = false
    },

    /** 导出按钮操作 */
    handleExport() {
      const fileName = this.$t('lead.exportFileName') + parseTime(new Date(), '{y}{m}{d}') + '.xlsx'
      this.download('business/lead/export', {
        ...this.queryParams,
        leadIds: this.ids || null
      }, fileName)
    },

    // getAgentName(areaId) {
    //   if (areaId !== null && areaId !== undefined && areaId >= 0) {
    //     const area = this.areaMap.get(areaId)
    //     if (area) {
    //       return area['areaName' + this.localLabelSuffix]
    //     }
    //   }
    //   return '-'
    // },

    submitConvertCust() {
      // 新客户
      if (this.isNewCustomer) {
        this.$tab.openPage(this.$t('account.add'), '/account-edit/index/' + 0, {
          type: 'add',
          leadIds: this.convertCustForm.leadIds
        })
        this.convertCustOpen = false
      } else {
        // 现有客户
        this.$refs['convertCustForm'].validate(async valid => {
          if (valid) {
            this.pageLoading = true
            try {
              if (this.convertCustForm.leadIds && this.convertCustForm.leadIds.length > 0) {
                this.convertCustForm.relativeAccount = this.convertCustForm.accountId
                await convertCust(this.convertCustForm)
              }
              this.getList()
            } catch (error) {
              console.error(error)
            } finally {
              this.pageLoading = false
            }
            this.convertCustOpen = false
          }
        })
      }

    },

    cancelConvert() {
      this.convertCustOpen = false
    },

  }
}
</script>


<style lang="scss" scoped>

.app-container {
  padding: 24px;
}

::v-deep .edit-dialog {
  .el-dialog__body {
    min-height: 50vh;
    max-height: 75vh;
    overflow: auto;
    padding: 30px 50px;
  }

  .el-dialog__footer {
    padding: 10px 50px 20px 50px;
  }

  .el-form-item--medium .el-form-item__content, .el-form-item--medium .el-form-item__label {
    line-height: 25px;
  }

  .el-form--label-top .el-form-item__label {
    padding: 0;
  }

  .el-form .el-row:last-child .el-form-item {
    margin-bottom: 0;
  }

  .vue-treeselect .vue-treeselect__control {
    padding: 0 10px;
  }
}

/* 更多 按钮 样式 start */
@import "@/assets/styles/element-variables.scss";
.el-dropdown-menu {
  padding: 8px 0;

  .el-dropdown-menu__item {
    padding: 0 20px;
    color: $--color-primary;
  }

  .el-dropdown-menu__item + .el-dropdown-menu__item {
    margin-top: 5px;
  }
}

::v-deep .el-dropdown-menu__item i {
  margin-right: 12px !important;
}

/* 更多 按钮 样式 end */


.w-100 {
  width: 100%;
}


</style>
