<template>
    <div class="account-container" v-loading="loading">
        <div class="top">
            <div class="account-title">{{ accountTitle }}</div>
            <div class="button-group">
                <el-button v-if="type != 'view'" type="primary" icon="el-icon-circle-check" @click="submitForm"
                    :loading="submitLoading">{{ $t('common.confirm') }}</el-button>
                <el-button v-if="type != 'view'" @click="cancel" icon="el-icon-remove-outline">
                    {{ $t('common.cancel') }}</el-button>
                <el-button v-if="type == 'view'" icon="el-icon-remove-outline" plain size="mini" @click="cancel">
                    {{ $t('common.back') }}</el-button>
            </div>
        </div>
        <!-- 客户选择 -->
        <div class="account-select">
            <div v-if="type != 'add' && accounts.length > 0" class="select-box">
                <div class="select-item" v-for="(item, index) in accounts" :key="index"
                    @click="selectAccount(item, index)" :class="{ 'selected': selectedIndex == index }">
                    {{ item.agentName == 'common.head' ? $t(item.agentName) : item.agentName }}
                </div>
            </div>
        </div>
        <div class="content">
            <!-- 左半边卡片 -->
            <!-- 客户基本信息 -->
            <div class="card card-base" :class="{ 'card-full': type != 'view' || $route.query.historyId }">
                <div class="flex-center-left mb16">
                    <img class="item-size" src="../../../assets/images/account-item.png" alt="">
                    <div class="card-title">{{ $t('account.baseInfo') }}</div>
                </div>
                <el-form class="account-form" ref="form" :model="form" :rules="type != 'view' ? rules : {}"
                    label-position="top">
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <!-- 区域 -->
                            <el-form-item :label="$t('user.area')" prop="areaId">
                                <!--<treeselect :class="{ 'treeselect': disableFlag }" v-model="form.areaId"-->
                                <!--    :style="disableFlag ? { width: '16vw' } : { width: '80%' }"-->
                                <!--    :options="areaTree" :placeholder="$t('common.pleaseSelect') + $t('user.area')"-->
                                <!--    :show-count="true" :disabled="disableFlag" :normalizer="normalizer"-->
                                <!--    @select="selectArea" @input="areaChange" />-->

                              <treeselect v-model="form.areaId" :flat="true" :options="areaTree" :noResultsText="$t('common.noResultsText')"
                                          :placeholder="$t('common.pleaseSelect') + $t('user.area')"
                                          :style="disableFlag ? { width: '16vw' } : { width: '80%' }"
                                          :show-count="true" class="w-100" :disabled="disableFlag"
                                          @input="areaChange" @select="selectArea">
                                <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="8">
                            <!-- 国家 -->
                            <Select :disabled="disableFlag" prop="countryId" :data="nationList"
                                :label="$t('account.country')" :required="!disableFlag"
                                :styleObj="disableFlag ? { width: '16vw' } : { width: '80%' }"></Select>
                        </el-col>
                        <el-col :span="8">
                            <!--&lt;!&ndash; 客户类型 &ndash;&gt;-->
                            <!--<Select :disabled="disableFlag" prop="type" :data="dict.type.account_type"-->
                            <!--    :label="$t('account.type')" :required="!disableFlag"-->
                            <!--    :styleObj="disableFlag ? { width: '16vw' } : { width: '80%' }"></Select>-->

                          <!-- 客户等级 -->
                          <Select :disabled="disableFlag" prop="level" :data="dict.type.account_level"
                                  :label="$t('account.level')" :required="!disableFlag"
                                  :styleObj="disableFlag ? { width: '16vw' } : { width: '80%' }"></Select>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="8">
                          <!-- 跟进状态 -->
                          <Select :disabled="disableFlag" prop="status" :data="dict.type.account_status"
                                  :label="$t('account.status')" :required="!disableFlag"
                                  :styleObj="disableFlag ? { width: '16vw' } : { width: '80%' }"></Select>
                        </el-col>
                        <el-col :span="8">
                            <!-- 公司名称 -->
                            <Input :disabled="disableFlag" prop="accountName" :label="$t('account.accountName')"
                                :width="disableFlag ? '16vw' : '80%'" :required="!disableFlag" :maxlength="100"></Input>
                        </el-col>
                        <el-col :span="8">
                            <!-- 公司类型 -->
                            <Select :disabled="disableFlag" prop="companyType" :data="dict.type.company_type"
                                :label="$t('account.companyType')" :required="!disableFlag"
                                :styleObj="disableFlag ? { width: '16vw' } : { width: '80%' }"></Select>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <!-- 公司地址 -->
                            <Input :disabled="disableFlag" prop="address" :label="$t('account.address')"
                                :width="disableFlag ? '16vw' : '80%'" :maxlength="100" ></Input>
                        </el-col>
                        <el-col :span="8">
                            <!-- 公司网址 -->
                            <Input :disabled="disableFlag" prop="companyWebsite" :label="$t('company.website')"
                                :width="disableFlag ? '16vw' : '80%'" :maxlength="100" ></Input>
                        </el-col>
                        <el-col :span="8">
                            <!-- 公司背景 -->
                            <Input :disabled="disableFlag" prop="background" :label="$t('company.background')"
                                :width="disableFlag ? '16vw' : '80%'" :maxlength="250" ></Input>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <!-- 归属集团 -->
                            <Input :disabled="disableFlag" prop="accountGroup" :label="$t('account.group')"
                                :width="disableFlag ? '16vw' : '80%'" :maxlength="100" ></Input>
                        </el-col>
                        <el-col :span="8">
                          <!-- 项目类型 -->
                          <Select :disabled="disableFlag" prop="segment" :data="dict.type.project_type"
                                  :label="$t('lead.segment')"
                                  :styleObj="disableFlag ? { width: '16vw' } : { width: '80%' }"></Select>
                        </el-col>
                        <el-col :span="8">
                            <!-- 产品意向 -->
                            <Select :disabled="disableFlag" prop="intentionalProduct"
                                :data="dict.type.intentional_product" :label="$t('account.intentionalProduct')"
                                :styleObj="disableFlag ? { width: '16vw' } : { width: '80%' }"></Select>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">

                        <el-col :span="8">
                            <!-- 首次合作年份 -->
                            <el-form-item :label="$t('project.beginYear')" prop="beginYear">
                                <el-date-picker :disabled="disableFlag" v-model="form.beginYear" type="year"
                                    :placeholder="$t('common.pleaseSelect') + $t('project.beginYear')"
                                    :style="disableFlag ? { width: '16vw' } : { width: '80%' }">
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <!-- 负责人 -->
                            <Select :disabled="disableFlag" prop="owner" :data="ownerList" :label="$t('agent.head')"
                                valueProp="userId" labelProp="nickName" :required="!disableFlag"
                                :styleObj="disableFlag ? { width: '16vw' } : { width: '80%' }"></Select>
                        </el-col>

                      <el-col :span="8">
                        <!-- 代理商 -->
                        <Select :disabled="disableFlag" prop="ownerAgent" :data="agentList" :label="$t('lead.agent')"
                                :styleObj="disableFlag ? { width: '16vw' } : { width: '80%' }"
                                valueProp="agentId" labelProp="agentName" :required="!disableFlag"></Select>
                      </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="16" v-if="type != 'view'">
                            <!-- 关联线索 -->
                            <PageSelect class="lead-select" :label="$t('account.lead')" prop="leadIds" width="90%"
                                :list="listByCurUser" :pageSize="10" valueProp="leadId" labelProp="leadNo"
                                :formatLabel="formatLeadLabel" multiple :visibleGetData="true" idName="leadId"
                                :defaultParams="{ relativeAccount: accountId ? accountId : null, language: $i18n.locale }"
                                :defaultData="defaultData" ref="pageSelect" @change="resetDefaultData"/>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="16" v-if="type != 'view'">
                          <!-- 备注 -->
                          <Input :disabled="disableFlag" prop="remark" :label="$t('common.remark')" width="90%"
                                 :maxlength="500"  type="textarea"></Input>
                        </el-col>
                    </el-row>



                    <el-form-item :label="$t('account.file')" prop="fileList">
                        <FileUpload :class="{ 'upload': disableFlag }" v-model="form.fileList" :isShowTip="false"
                            :fileType="fileType" :disabled="disableFlag" :buttonText="$t('common.uploadFile')">
                        </FileUpload>
                    </el-form-item>
                </el-form>

              <el-divider></el-divider>

                <!-- 添加联系人 -->
                <div :class="{ 'contact-box': type != 'view' }">
                    <div class="flex-center-left mb16">
                        <img class="item-size" src="../../../assets/images/account-item.png" alt="">
                        <div class="card-title">{{ $t('account.contact') }}</div>
                    </div>
                    <div v-if="type != 'view'" class="mb16">
                        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addLine">
                            {{ $t('account.addLine') }}</el-button>
                        <el-button size="mini" plain icon="el-icon-delete" @click="deleteLine"
                            :disabled="deleteDisabled">
                            {{ $t('account.deleteLine') }}</el-button>
                    </div>
                    <el-table :data="contactList" @selection-change="handleSelectionChange" max-height="280px" border
                        :header-cell-style="{ background: '#F4F6F8', color: '#92A2B5' }">
                        <el-table-column v-if="type != 'view'" type="selection" width="55"></el-table-column>
                        <el-table-column prop="contactName" :label="$t('contact.name')" width="200px">
                            <template slot-scope="scope">
                                <el-input v-model.trim="scope.row.contactName" :disabled="type == 'view'"
                                    maxlength="30"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="phone" :label="$t('contact.phone')" width="200px">
                            <template slot-scope="scope">
                                <el-input v-model.trim="scope.row.phone" :disabled="type == 'view'"
                                    maxlength="30"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="address" :label="$t('contact.address')" width="200px">
                            <template slot-scope="scope">
                                <el-input v-model.trim="scope.row.address" :disabled="type == 'view'"
                                    maxlength="100"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="email" :label="$t('contact.email')" width="200px">
                            <template slot-scope="scope">
                                <el-input v-model.trim="scope.row.email" :disabled="type == 'view'"
                                    maxlength="50"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="jobTitle" :label="$t('contact.job')" width="200px">
                            <template slot-scope="scope">
                                <el-input v-model.trim="scope.row.jobTitle" :disabled="type == 'view'"
                                    maxlength="100"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="birthday" :label="$t('contact.birthday')" width="200px">
                            <template slot-scope="scope">
                                <el-date-picker v-model="scope.row.birthday" type="date" :disabled="type == 'view'">
                                </el-date-picker>
                            </template>
                        </el-table-column>
                        <el-table-column prop="horoscope" :label="$t('contact.horoscope')" width="200px">
                            <template slot-scope="scope">
                                <el-input v-model.trim="scope.row.horoscope" :disabled="type == 'view'"
                                    maxlength="20"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="maritalStatus" :label="$t('contact.maritalStatus')" width="200px">
                            <template slot-scope="scope">
                                <el-select :disabled="type == 'view'" v-model="scope.row.maritalStatus" clearable>
                                    <el-option v-for="dict in dict.type.marital_status" :key="dict.value"
                                        :label="dict.label" :value="dict.value" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column prop="hobbies" :label="$t('contact.hobbies')" width="200px">
                            <template slot-scope="scope">
                                <el-input v-model="scope.row.hobbies" :disabled="type == 'view'"
                                    maxlength="100"></el-input>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <!-- 右半边卡片 -->
            <div class="ml20" v-if="type == 'view' && !$route.query.historyId">
              <div class="card card-mini follow-list mb16" v-hasPermi="['business:account:follow']" v-if="hasPermission()">
                <!-- 快速跟进 -->
                <div class="title-row">
                  <div class="flex-center-left mb16">
                    <img alt="" class="item-size" src="../../../assets/images/account-item.png">
                    <div class="card-title">{{ $t('follow.fastTrack') }}</div>
                  </div>
                  <el-button size="mini" type="primary" @click="handleAddFollow">{{ $t('common.add') }}</el-button>
                </div>
                <el-form ref="fastFollowForm" :model="fastFollowForm" label-position="top">
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <!-- 跟进方式 -->
                      <Select :data="dict.type.crm_follow_way" :label="$t('follow.followWay')" prop="followWay"
                              required/>
                    </el-col>
                    <el-col :span="8">
                      <!--联系人-->
                      <Select :data="contactList" :label="$t('follow.contactPerson')" clearable allow-create
                              filterable label-prop="contactName" prop="contactPerson" @change="contactPersonChange"
                              required value-prop="contactId"/>
                    </el-col>
                    <el-col :span="8">
                      <!--联系方式-->
                      <Input :label="$t('common.contact')" prop="contact" required width="100%"/>
                    </el-col>
                  </el-row>
                  <!-- 跟进内容及结果 -->
                  <Input :label="$t('follow.followDesc')" prop="followDesc" required width="100%"/>
                </el-form>
              </div>

                <!-- 跟进记录 -->
                <div class="card card-mini">
                  <div class="flex-center-left mb16">
                    <img class="item-size" src="../../../assets/images/account-item.png" alt="">
                    <div class="card-title">{{ $t('account.follow') }}</div>
                  </div>
                  <el-table :data="followList" max-height="280px" border
                            :header-cell-style="{ background: '#F4F6F8', color: '#92A2B5' }">
                            <el-table-column align="center" label="No" type="index" width="50"/>

                    <!-- <el-table-column prop="followNo" :label="$t('follow.no')" width="200px"></el-table-column> -->
                    <el-table-column prop="followTime" :label="$t('follow.time')" width="100px">
                      <template slot-scope="scope">
                        {{ getLocalTime(scope.row.followTime, 'YYYY-MM-DD') }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="contactPerson" :label="$t('common.contactPerson')" show-overflow-tooltip
                                     width="120px"></el-table-column>
                    <el-table-column prop="contact" :label="$t('common.contact')" width="120px" show-overflow-tooltip></el-table-column>
                    <!-- <el-table-column prop="createByName" :label="$t('account.followPerson')" show-overflow-tooltip
                                     width="120px"></el-table-column> -->
                     <el-table-column prop="followDesc" :label="$t('account.followDesc')" show-overflow-tooltip
                                     ></el-table-column>
                    <!-- <el-table-column prop="createTime" :label="$t('common.createTime')"
                        width="200px"></el-table-column> -->
                    <el-table-column :label="$t('common.operate')" width="100px" fixed="right" align="center">
                      <template slot-scope="scope">
                        <el-button size="mini" type="text" icon="el-icon-view"
                                   @click="handleViewFollow(scope.row)">{{ $t('common.view') }}</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                  <pagination :auto-scroll="false" :total="followTotal" :page.sync="followQueryParams.pageNum"
                              :limit.sync="followQueryParams.pageSize" @pagination="getFollowListByAccount" />

              </div>
                <!-- 关联线索 -->
                <div class="card card-mini mt16">
                    <div class="flex-center-left mb16">
                        <img class="item-size" src="../../../assets/images/account-item.png" alt="">
                        <div class="card-title">{{ $t('account.lead') }}</div>
                    </div>
                    <el-table :data="leadList" max-height="280px" border
                        :header-cell-style="{ background: '#F4F6F8', color: '#92A2B5' }">
                        <el-table-column prop="leadNo" :label="$t('lead.leadNo')" width="200px"></el-table-column>
                        <el-table-column prop="areaName" :label="$t('lead.area')" width="200px"></el-table-column>
                        <el-table-column prop="company" :label="$t('lead.company')" width="200px"></el-table-column>
                        <el-table-column prop="origin" :label="$t('lead.origin')" width="200px">
                            <template slot-scope="scope">
                                <span>{{ formatDict(scope.row.origin, dict.type.lead_source) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="contactPerson" :label="$t('common.contactPerson')"
                            width="200px"></el-table-column>
                        <el-table-column prop="contact" :label="$t('common.contact')" width="200px"></el-table-column>
                        <el-table-column prop="createByName" :label="$t('common.createBy')"
                            width="200px"></el-table-column>
                        <el-table-column prop="createTime" :label="$t('common.createTime')"
                            width="200px"></el-table-column>
                        <el-table-column :label="$t('common.operate')" width="100px" fixed="right" align="center">
                            <template slot-scope="scope">
                                <el-button size="mini" type="text" icon="el-icon-view"
                                    @click="handleViewLead(scope.row)">{{ $t('common.view') }}</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination :auto-scroll="false" :total="leadTotal" :page.sync="leadQueryParams.pageNum"
                        :limit.sync="leadQueryParams.pageSize" @pagination="getLeadListByAccount" />
                </div>
                <!-- 关联项目 -->
                <div class="card card-mini mt16">
                    <div class="flex-center-left mb16">
                        <img class="item-size" src="../../../assets/images/account-item.png" alt="">
                        <div class="card-title">{{ $t('account.project') }}</div>
                    </div>
                    <el-table :data="projectList" max-height="280px" border
                        :header-cell-style="{ background: '#F4F6F8', color: '#92A2B5' }">
                        <el-table-column prop="projectNo" :label="$t('project.no')" width="200px"></el-table-column>
                        <el-table-column prop="projectName" :label="$t('project.name')" width="250px"></el-table-column>
                        <el-table-column prop="type" :label="$t('lead.segment')" width="200px">
                            <template slot-scope="scope">
                                <span>{{ formatDict(scope.row.type, dict.type.project_type) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="contactPerson" :label="$t('common.contactPerson')"
                            width="200px"></el-table-column>
                        <el-table-column prop="contact" :label="$t('common.contact')" width="200px"></el-table-column>
                        <el-table-column prop="createByName" :label="$t('common.createBy')"
                            width="200px"></el-table-column>
                        <el-table-column prop="createTime" :label="$t('common.createTime')"
                            width="200px"></el-table-column>
                        <el-table-column :label="$t('common.operate')" width="100px" fixed="right" align="center">
                            <template slot-scope="scope">
                                <el-button size="mini" type="text" icon="el-icon-view"
                                    @click="handleViewProject(scope.row)">{{ $t('common.view') }}</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination :auto-scroll="false" :total="projectTotal" :page.sync="projectQueryParams.pageNum"
                        :limit.sync="projectQueryParams.pageSize" @pagination="getProjectListByAccount" />
                </div>

            </div>
        </div>
        <!-- 线索选择器 -->
        <el-dialog :title="$t('lead.select')" :visible.sync="leadOpen" width="1000px" :before-close="closeLead"
            append-to-body :close-on-click-modal="false">
            <card-table :modalData="leadOption" :searchParams="selectLeadParams" @pagination="getMyLeadList"
                :loading="leadLoading" :tableSearch="true" @columnSearch="handleLeadQuery" @resetList="resetLeadQuery">
                <template #default="{ list }">
                    <!-- <el-table-column type="selection" width="50" align="center" /> -->
                    <el-table-column label="No." type="index" width="50" align="center" />
                    <!--线索编号-->
                    <Column :label="$t('lead.leadNo')" :showSearch="true" prop="leadNo" width="200" />
                    <!--公司-->
                    <Column :label="$t('lead.company')" :showSearch="true" prop="company" width="200" />
                    <!--行业-->
                    <Column :label="$t('lead.sector')" :searchDict="dict.type.lead_industry" :showSearch="true"
                        prop="sector" searchType="select" selectMore width="200" />
                    <!--联系人-->
                    <Column :label="$t('lead.contactPerson')" :showSearch="true" prop="contactPerson" width="200" />
                    <!--联系方式-->
                    <!-- <Column :label="$t('lead.contact')" :showSearch="true" prop="contact" width="200" /> -->
                    <Column :label="$t('common.operate')" :min-width="250" fixed="right" :showSearch="true"
                        searchType="operate">
                        <template #default="{ row }">
                            <el-button size="mini" type="text" icon="el-icon-plus" @click="addLead(row)">{{
                                $t('common.addNew') }}</el-button>
                        </template>
                    </Column>
                </template>
            </card-table>
            <div style="margin-top: 24px;font-size: 16px;">{{ $t('lead.selected') }}</div>
            <el-table style="margin-top: 20px;" :data="selectLeadList" max-height="300px" border
                :header-cell-style="{ background: '#F4F6F8', color: '#92A2B5' }">
                <el-table-column label="No." type="index" width="50" align="center" />
                <el-table-column prop="leadNo" :label="$t('lead.leadNo')" width="200px"
                    show-overflow-tooltip></el-table-column>
                <el-table-column prop="company" :label="$t('lead.company')" width="200px"
                    show-overflow-tooltip></el-table-column>
                <el-table-column prop="sector" :label="$t('lead.sector')" width="200px" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <span>{{ formatDict(scope.row.sector, dict.type.lead_industry) }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="contactPerson" :label="$t('lead.contactPerson')" width="200px"
                    show-overflow-tooltip></el-table-column>
                <!-- <el-table-column prop="contact" :label="$t('lead.contact')" width="200px"></el-table-column> -->
                <el-table-column :label="$t('common.operate')" width="150px" fixed="right" align="center">
                    <template slot-scope="scope">
                        <el-button size="mini" type="text" icon="el-icon-delete" @click="deleteLead(scope.row)">
                            {{ $t('common.delete') }}</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" icon="el-icon-circle-check" @click="confirmSelect">{{ $t('common.confirm')
                    }}</el-button>
                <el-button @click="closeLead" icon="el-icon-remove-outline">{{ $t('common.cancel') }}</el-button>
            </div>
        </el-dialog>
        <FollowDialog ref="followDialog"></FollowDialog>
    </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getAreaTreeByUser } from "@/api/common/common";
import { getAccount, addAccount, updateAccount } from "@/api/business/crm/account";
import { getHistory } from "@/api/business/crm/accountHistory";
import { getAllNationList } from "@/api/user/country";
import { getRelatedContact } from "@/api/business/crm/contact";
import { selectProjectListByAccount } from "@/api/business/crm/project";
import { addFollow, selectFollowListByAccount } from '@/api/business/crm/follow'
import { getOwnerList, getAllOwnerList } from "@/api/system/user";
import { allList, listByCurUser, selectLeadListByAccount } from "@/api/business/crm/lead";
import { getCountryByAreaId } from "@/api/system/user";
import FileUpload from "@/components/FileUpload";
import { getLocalTime } from "@/utils/data/dataUtils"
import FollowDialog from "@/views/crmManagement/follow/FollowDialog";
import CommonSelect from "../../../components/element/form/items/CommonSelect";
import PageSelect from "../../../components/element/form/items/PageSelect";
import { selectByOwner } from '@/api/user/agent'
import { isEmptyObject } from '@/utils/validate'

export default {
    name: "accountEdit",
    dicts: ['account_status', 'account_level', 'account_type', 'intentional_product', 'lead_source', 'lead_industry', 'marital_status', 'project_type', 'company_type', 'crm_follow_way'],
    components: { PageSelect, CommonSelect, FileUpload, Treeselect, FollowDialog },
    data() {
        return {
            accountId: null,
            type: '',
            form: {
                fileList: [],
                leadIds: []
            },
            rules: {
                areaId: [
                    { required: true, message: this.$t('common.pleaseSelect') + this.$t('user.area'), trigger: "change" }
                ],
            },
            nationList: [],
            areaList: [],
            contactList: [],
            contactShowList: [],
            leadList: [],
            myLeadList: [],
            projectList: [],
            followList: [],
            ownerList: [],
            multipleSelection: [],
            deleteDisabled: true,
            fileType: ["jpg", "png", "jpeg", "doc", "docx", "xls", "xlsx", "ppt", "txt", "pdf"],
            leadQueryParams: {
                pageNum: 1,
                pageSize: 10,
            },
            leadTotal: 0,
            projectQueryParams: {
                pageNum: 1,
                pageSize: 10,
            },
            projectTotal: 0,
            followQueryParams: {
                pageNum: 1,
                pageSize: 10,
            },
            followTotal: 0,
            selectedIndex: 0,
            accounts: [],
            accountTitle: '',
            areaTree: [],
            disableFlag: false,
            language: null,
            loading: false,
            submitLoading: false,
            leadLoading: false,
            leadOpen: false,
            leadOption: [],
            selectLeadParams: {
                pageNum: 1,
                pageSize: 10,
            },
            selectLeadList: [],
            defaultData: [],

            agentList: [],
            fastFollowForm: {
              followType: '1',
              followWay: null,
              followDesc: null,
              contactPerson: null,
            }
        };
    },

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

    async created() {
        this.permissionChar = this.$store.state.user.permissionChar
        this.language = this.$i18n.locale;
        this.initType();
        this.accountId = this.$route.params && this.$route.params.accountId;
        this.leadQueryParams.pageNum = 1;
        this.projectQueryParams.pageNum = 1;
        this.followQueryParams.pageNum = 1;
        this.loading = true;
        try {
            this.getAreaTree();
            await this.getAgentListByOwner();

            if (this.type != 'add') {
                if (this.$route.query.historyId) {
                    getHistory(this.$route.query.historyId).then(response => {
                        this.form = response.data;
                        this.contactList = response.data.contactList;
                        if (this.form.fileList && this.form.fileList.length > 0) {
                            this.form.fileList = this.form.fileList.map(item => {
                                return {
                                    // name: item.realFileName,
                                    name: item.serverFileName,
                                    url: item.filePath
                                }
                            })
                        } else {
                            this.form.fileList = [];
                        }
                    })
                } else {

                    if (this.type == 'view') {
                        this.getAccount(true);
                    } else {
                        this.getAccount(false);
                    }
                    this.getRelatedContact();
                }
                if (this.type == 'view') {
                    this.getAllOwnerList();
                    if (!this.$route.query.historyId) {
                        this.getLeadListByAccount();
                        this.getProjectListByAccount();
                        this.getFollowListByAccount();
                    }
                } else {
                    this.getOwnerList();
                }
            } else {
                this.getOwnerList();
                // 状态设置默认值
                this.$set(this.form, 'type', '');
                this.$set(this.form, 'origin', '');
                this.$set(this.form, 'sector', '');
                // this.$set(this.form, 'countryId', '');
                this.$set(this.form, 'level', '1');
                this.$set(this.form, 'status', '1');
                this.$set(this.form, 'orderStatus', '0');
                let userId = this.$store.state.user.id;
                this.$set(this.form, 'owner', userId == 1 ? null : userId);

                // this.$refs.form.clearValidate();
                if (this.$route.query.leadIds) {
                    let leadIds = this.$route.query.leadIds;
                    allList({ leadIds: leadIds }).then(response => {
                        let leadData = response.data[0]
                        this.$set(this.form, 'accountName', leadData.company);
                        this.$set(this.form, 'type', leadData.type);
                        this.$set(this.form, 'countryId', leadData.countryId);
                        if (leadData.sector) {
                            this.$set(this.form, 'sector', leadData.sector);
                        }
                        this.$set(this.form, 'areaId', leadData.areaId);
                        this.$set(this.form, 'email', leadData.email);
                        this.$set(this.form, 'phone', leadData.contact);
                        this.$set(this.form, 'address', leadData.address);
                        this.$set(this.form, 'origin', leadData.origin);
                        // 公司类型
                        this.$set(this.form, 'companyType', leadData.companyType);
                        // 公司背景
                        this.$set(this.form, 'background', leadData.background);
                        // 所属集团
                        this.$set(this.form, 'accountGroup', leadData.group);
                        // 产品意向
                        this.$set(this.form, 'intentionalProduct', leadData.intentionalProduct);
                        // 项目类型
                        this.$set(this.form, 'segment', leadData.segment);
                        // 联系人
                        this.contactList.push({
                            contactName: leadData.contactPerson,
                            phone: leadData.contact,
                            email: leadData.email,
                            jobTitle: leadData.jobTitle,
                        });

                        this.myLeadList = response.data.map(item => {
                            return {
                                value: item.leadId,
                                label: item.leadNo
                                    + ': 【' + (item.areaName || '') + '】'
                                    + ' 【' + (item.company || '') + '】'
                                    + ' 【' + (item.contactPerson || '') + '】'
                                // + ' 【' + (this.formatDict(item.sector, this.dict.type.lead_industry) || '') + '】'
                            };
                        });
                        this.defaultData = response.data
                        this.$refs.pageSelect.data = this.defaultData
                        this.$refs.pageSelect.resSet()
                    });
                    if (leadIds) {
                        this.$set(this.form, 'leadIds', leadIds.map(item => Number(item)))
                    }
                }
            }
        } finally {
            this.loading = false;
        }
    },
    activated() {
        this.initType();
        const obj = Object.assign({}, this.$route, { title: this.accountTitle })
        this.$tab.updatePage(obj);
    },
    methods: {
        listByCurUser,
        formatLeadLabel(leadNo, item) {
            return item.leadNo
                + ': 【' + (item.areaName || '') + '】'
                + ' 【' + (item.company || '') + '】'
                + ' 【' + (item.contactPerson || '') + '】'
            // + ' 【' + (this.formatDict(item.sector, this.dict.type.lead_industry) || '') + '】'
        },

        getLocalTime,
        selectAccount(item, index) {
            // 如果切换客户
            if (this.selectedIndex != index) {
                this.selectedIndex = index;
                this.accountId = item.accountId;
                this.getAccount(false);
                this.getRelatedContact();
                if (this.type == 'view' && !this.$route.query.data) {
                    this.getLeadListByAccount();
                    this.getProjectListByAccount();
                    this.getFollowListByAccount();
                }
                // 只有主客户可以编辑
                if (this.type == 'edit') {
                    if (index != 0) {
                        this.$set(this, 'disableFlag', true);
                    } else {
                        this.$set(this, 'disableFlag', false);
                    }
                }
            }
        },
        // 打开线索选择器
        async openlead() {
            this.selectLeadList = [];
            this.leadOpen = true;
            await this.getMyLeadList();
            if (this.form.leadIds) {
                this.form.leadIds.forEach(leadId => {
                    let lead = this.leadOption.find(x => x.leadId == leadId);
                    this.selectLeadList.push({
                        leadId: lead.leadId,
                        leadNo: lead.leadNo,
                        areaId: lead.areaId,
                        areaName: lead.areaName,
                        company: lead.company,
                        contactPerson: lead.contactPerson,
                        // contact: lead.contact,
                        sector: lead.sector
                    });
                })
            }
        },
        // 关闭线索选择器
        closeLead() {
            this.leadOpen = false;
        },
        // 添加线索
        addLead(row) {
            // 去重
            if (this.selectLeadList.some(item => item.leadId == row.leadId)) {
                return;
            }
            this.selectLeadList.push({
                leadId: row.leadId,
                leadNo: row.leadNo,
                areaId: row.areaId,
                areaName: row.areaName,
                company: row.company,
                contactPerson: row.contactPerson,
                // contact: row.contact,
                sector: row.sector
            })
        },
        // 删除线索
        deleteLead(row) {
            this.selectLeadList = this.selectLeadList.filter(item => item.leadId != row.leadId)
        },
        // 线索确认选择
        confirmSelect() {
            if (this.selectLeadList.length > 0) {
                this.$set(this.form, 'leadIds', this.selectLeadList.map(item => item.leadId));
                this.myLeadList = this.selectLeadList.map(item => {
                    return {
                        value: item.leadId,
                        label: item.leadNo
                            + ': 【' + (item.areaName || '') + '】'
                            + ' 【' + (item.company || '') + '】'
                            + ' 【' + (item.contactPerson || '') + '】'
                            + ' 【' + (this.formatDict(item.sector, this.dict.type.lead_industry) || '') + '】'
                    };
                });
            } else {
                this.$set(this.form, 'leadIds', null);
            }
            this.leadOpen = false;
        },
        handleLeadQuery() {
            this.selectLeadParams.pageNum = 1;
            this.getMyLeadList();
        },
        resetLeadQuery() {
            this.$set(this.selectLeadParams, "pageNum", 1);
            this.$set(this.selectLeadParams, "pageSize", 10);
            this.$set(this.selectLeadParams, "leadNo", null);
            this.$set(this.selectLeadParams, "contactPerson", null);
            this.$set(this.selectLeadParams, "sector", null);
            this.$set(this.selectLeadParams, "company", null);
            this.getMyLeadList();
        },
        initType() {
            this.type = this.$route.query && this.$route.query.type;
            switch (this.type) {
                case 'add':
                    this.accountTitle = this.$t('account.add');
                    break;
                case 'edit':
                    this.accountTitle = this.$t('account.edit');
                    break;
                case 'view':
                    this.accountTitle = this.$t('account.view');
                    break;
            }
            this.disableFlag = this.type == 'view';
        },
        // 区域发生变化
        async areaChange(val) {
            // 表单重新校验区域
            this.$refs['form'].validateField(['areaId']);
            if (val) {
                await this.getCountryByAreaId(val)
            }
        },
        async selectArea(val) {
            this.$set(this.form, "countryId", null);
            // this.nationList = []
            // if (val.id) {
            //     await this.getCountryByAreaId(val.id)
            // }
        },
        async getCountryByAreaId(areaId) {
            const resp = await getCountryByAreaId(areaId);
            this.nationList = resp.data.map(item => {
                let label = '';
                switch (this.language) {
                    case 'chinese':
                        label = item.countryName
                        break;
                    case 'english':
                        label = item.countryNameUS
                        break;
                    case 'russia':
                        label = item.countryNameRU
                        break;
                    case 'spanish':
                        label = item.countryNameES
                        break;
                }
                return {
                    value: item.countryId,
                    label: label
                }
            });
        },
        // 获取地区树
        getAreaTree() {
            getAreaTreeByUser().then(response => {
                this.areaTree = response.data;
            });
        },
        normalizer(node) {
            switch (this.language) {
                case 'chinese':
                    return {
                        label: node.label,
                    };
                case 'english':
                    return {
                        label: node.labelES,
                    };
                case 'russia':
                    return {
                        label: node.labelRU,
                    };
                case 'spanish':
                    return {
                        label: node.labelUS,
                    };
            }
        },
        /** 获取字典数据匹配的值 */
        formatDict(value, dictData) {
            return dictData.find(dict => dict.value == value)?.label;
        },
        /** 查询客户可选线索列表 */
        async getMyLeadList() {
            this.leadLoading = true;
            this.selectLeadParams.language = this.language;
            if (this.accountId && this.accountId != 0) {
                this.selectLeadParams.relativeAccount = this.accountId;
            }
            await listByCurUser(this.selectLeadParams).then(response => {
                this.leadOption = response.rows;
                this.selectLeadParams.total = response.total;
            });
            this.leadLoading = false;
        },
        /** 查询客户所有人列表 */
        getOwnerList() {
            getOwnerList({onlySalesRole: true}).then(response => {
                this.ownerList = response.data;
            })
        },
        getAllOwnerList() {
            getAllOwnerList({onlySalesRole: true}).then(response => {
                this.ownerList = response.data;
            })
        },
        /** 获取所有国家列表 */
        getNationList() {
            getAllNationList().then(response => {
                this.nationList = response.data.map(item => {
                    let label = '';
                    switch (this.language) {
                        case 'chinese':
                            label = item.countryName
                            break;
                        case 'english':
                            label = item.countryNameUS
                            break;
                        case 'russia':
                            label = item.countryNameRU
                            break;
                        case 'spanish':
                            label = item.countryNameES
                            break;
                    }
                    return {
                        value: item.countryId,
                        label: label
                    }
                });
            })
        },
        /** 查询客户关联线索 */
        getLeadListByAccount() {
            this.leadQueryParams.relativeAccount = this.accountId
            this.leadQueryParams.language = this.language;
            selectLeadListByAccount(this.leadQueryParams).then(response => {
                this.leadList = response.rows;
                this.leadTotal = response.total;
            })
        },
        /** 查询客户关联项目 */
        getProjectListByAccount() {
            this.projectQueryParams.accountId = this.accountId
            selectProjectListByAccount(this.projectQueryParams).then(response => {
                this.projectList = response.rows;
                this.projectTotal = response.total;
            })
        },
        /** 查询客户关联跟进记录 */
        getFollowListByAccount() {
            this.followQueryParams.businessId = this.accountId;
            selectFollowListByAccount(this.followQueryParams).then(response => {
                this.followList = response.rows;
                this.followTotal = response.total;
            })
        },
        /** 查询相关联系人 */
        getRelatedContact() {
            getRelatedContact({ accountId: this.accountId }).then(response => {
                this.contactList = response.rows;
                for (let i = 0; i < this.contactList.length; i++) {
                    this.contactList[i].index = i;
                }
            })
        },
        /** 多选联系人 */
        handleSelectionChange(val) {
            this.multipleSelection = val;
            this.deleteDisabled = this.multipleSelection.length === 0;
        },
        /** 新增联系人 */
        addLine() {
            this.contactList.push({
                index: this.contactList.length,
                accountId: this.accountId
            })
        },
        /** 删除联系人 */
        deleteLine() {
            this.multipleSelection.forEach(account => {
                this.contactList = this.contactList.filter(item => {
                    return item.index !== account.index;
                });
            });
            for (let i = 0; i < this.contactList.length; i++) {
                this.contactList[i].index = i;
            }
        },
        /** 返回上个页面 */
        cancel() {
            this.$tab.closePage();
        },
        /** 查询客户详情 */
        async getAccount(flag) {
            if (this.accountId != 0) {
                await getAccount(this.accountId).then(response => {
                    this.form = response.data;
                    // 处理线索
                    if (this.form.leadList.length > 0) {
                        // this.myLeadList = this.form.leadList.map(item => {
                        //     return {
                        //         value: item.leadId,
                        //         label: item.leadNo
                        //             + ': 【' + (item.areaName || '') + '】'
                        //             + ' 【' + (item.company || '') + '】'
                        //             + ' 【' + (item.contactPerson || '') + '】'
                        //             + ' 【' + (this.formatDict(item.sector, this.dict.type.lead_industry) || '') + '】'
                        //     };
                        // });

                      this.defaultData = JSON.parse(JSON.stringify(this.form.leadList));
                      setTimeout(() => {
                        this.$refs.pageSelect.data = this.defaultData
                        this.$refs.pageSelect.resSet()
                      }, 0)
                    }
                    if (flag) {
                        this.accounts = response.data.accounts || []
                        if (this.accounts.length > 0) {
                            this.accounts.unshift({
                                accountId: this.accountId,
                                agentName: this.form.agentName
                            })
                        }
                    }
                    if (this.form.fileList && this.form.fileList.length > 0) {
                        this.form.fileList = this.form.fileList.map(item => {
                            return {
                                // name: item.realFileName,
                                name: item.serverFileName,
                                url: item.filePath
                            }
                        })
                    } else {
                        this.form.fileList = [];
                    }
                });
            }
        },
        /** 提交按钮 */
        submitForm: function () {
            // 检验联系人姓名必填，联系方式/邮箱 两者必有其一
            if (this.contactList && this.contactList.length > 0) {
                let flag = false;
                this.contactList.forEach(item => {
                    if (!item.contactName || (!item.phone && !item.email)) {
                        flag = true;
                        return;
                    }
                });
                if (flag) {
                    this.$modal.msgError(this.$t('account.contactRequired'));
                    return;
                }
            }
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.submitLoading = true;
                    let account = Object.assign({}, this.form);
                    account.contactList = this.contactList;
                    // 处理附件
                    if (Array.isArray(account.fileList)) {
                        account.file = ''
                    } else {
                        account.file = account.fileList
                    }
                    delete account.fileList
                    delete account.accounts
                    if (this.accountId != 0) {
                        account.accountId = this.accountId
                        updateAccount(account).then(response => {
                            if (response.code == 200) {
                                this.$modal.msgSuccess(this.$t('common.editSuccess'));
                                this.$tab.closeOpenPage({ path: "/account" });
                                this.$store.commit('getAccountList');
                            } else {
                                this.$modal.msgError(response.msg);
                            }
                        }).catch(() => { });
                    } else {
                        account.accountId = null
                        addAccount(account).then(response => {
                            if (response.code == 200) {
                                this.$modal.msgSuccess(this.$t('common.addSuccess'));
                                if (this.$route.query.leadIds) {
                                    this.$tab.closeOpenPage({ path: "/lead" });
                                    this.$store.commit('refreshLead');
                                } else {
                                    this.$tab.closeOpenPage({ path: "/account" });
                                    this.$store.commit('getAccountList');
                                }
                            } else {
                                this.$modal.msgError(response.msg);
                            }
                        }).catch(() => { });
                    }
                    this.submitLoading = false;
                }
            });
        },
        handleViewLead(row) {
            this.$tab.openPage(this.$t('lead.detail'), '/crmManagement/lead-view/index/' + row.leadId);
        },
        handleViewProject(row) {
            this.$tab.openPage(this.$t('project.view'), '/project-view/' + row.projectId);
        },
        handleViewFollow(row) {
            let param = {
                flag: '3',
                followId: row.followId,
                leadId: null,
                accountId: null,
                projectId: this.projectId
            }
            this.$refs.followDialog.dialogItemInit(param);
        },
      resetDefaultData(row){
          this.defaultData = row
        console.log('row::', row)
        if (!row || row.length === 0) {
          this.$refs.form&&this.$refs.form.resetFields()
          this.contactList = []
          return
        }

        this.$nextTick(() => {
          // 区域
          this.$set(this.form, 'areaId', row[0].areaId);
          // 国家
          this.$set(this.form, 'countryId', row[0].countryId);
          // 公司类型
          this.$set(this.form, 'companyType', row[0].companyType);
          // 公司背景
          this.$set(this.form, 'background', row[0].background);
          // 所属集团
          this.$set(this.form, 'accountGroup', row[0].group);
          // 产品意向
          this.$set(this.form, 'intentionalProduct', row[0].intentionalProduct);
          // 项目类型
          this.$set(this.form, 'segment', row[0].segment);
          // 联系人
          this.contactList.push({
            contactName: row[0].contactPerson,
            phone: row[0].contact,
            email: row[0].email,
            jobTitle: row[0].jobTitle,
          });
          console.log('form::', this.form)
          console.log('contactList::', this.contactList)
        })


        // this.$forceUpdate()
      },

      getAgentListByOwner() {
        return selectByOwner(this.$store.getters.userId).then(res => {
          this.agentList = res.data;
          // 默认选中第一个
          if (!this.form.ownerAgent && this.agentList.length > 0) {
            this.form.ownerAgent = this.agentList[0].agentId;
          }
        })
      },

      contactPersonChange(res) {
        console.log('contactPerson change:::', res)
        if (!isEmptyObject(res)) {
          this.fastFollowForm.contactPerson = res.contactName
          this.fastFollowForm.contact = res.phone
          this.fastFollowForm.contactPersonName = res.contactName
        } else {
          // allow-create
          this.fastFollowForm.contactPerson = this.fastFollowForm.contactPerson || ''
          this.fastFollowForm.contactPersonName = this.fastFollowForm.contactPersonName || this.fastFollowForm.contactPerson

        }
      },

      handleAddFollow() {
        // 校验成功发送请求
        console.log('fast:', this.fastFollowForm)
        this.$refs.fastFollowForm.validate(async valid => {
          if (valid) {
            this.fastFollowForm.businessId = this.form.accountId;
            this.fastFollowForm.followTime = new Date();

            const response = await addFollow(this.fastFollowForm);
            if (response.code === 200) {
              this.$modal.msgSuccess(this.$t('common.addSuccess'));
              this.$refs.fastFollowForm.resetFields();
              this.getFollowListByAccount();
            } else {
              this.$modal.msgError(response.msg);
            }

          }
        })
      },

      /** 判断是否有权限 */
      hasPermission() {
        if (!this.form.permissionChar) {
          return false;
        }
        let flag = true;
        let permissionArray = this.permissionChar.split(',');
        let rowPermissionArray = this.form.permissionChar.split(',');
        for (let i = 0; i < rowPermissionArray.length; i++) {
          if (!permissionArray.includes(rowPermissionArray[i])) {
            flag = false;
            break;
          }
        }
        return flag;
      },
    }
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
::v-deep .account-form .el-form-item--medium .el-form-item__label {
    line-height: 10px;
}

::v-deep .el-form-item {
    margin-bottom: 20px;
}

::v-deep .upload-file-list .ele-upload-list__item-content {
    width: 500px;
}

::v-deep .upload {
    .upload-file-uploader {
        height: 0;
    }
}

::v-deep .el-link.el-link--default {
    padding-left: 15px;
}

//::v-deep .treeselect {
//    .vue-treeselect__single-value {
//        color: #C0C4CC;
//    }
//
//    .vue-treeselect__control {
//        border-color: #E4E7ED;
//        background-color: #F5F7FA;
//    }
//}

.account-container {
    padding: 16px 1vw;

    .account-title {
        font-family: Arial, Arial;
        font-weight: bold;
        font-size: 18px;
        line-height: 21px;
    }

    .input-width {
        width: 48vw;
    }

    .mt16 {
        margin-top: 16px;
    }

    .mb16 {
        margin-bottom: 16px;
    }

    .ml20 {
        margin-left: 1vw;
    }

    .top {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .button-group {
        display: flex;
    }

    .contact-box {
        margin-bottom: 50px;
    }

    .max-width {
        max-width: 20vw;
    }

    .flex-center-left {
        display: flex;
        align-items: center;
        justify-content: left;
    }

    .account-select {
        margin: 16px 0;
    }

    .select-box {
        display: flex;
    }

    .select-item {
        cursor: pointer;
        margin-right: 10px;
        padding: 10px 20px;
        font-family: Arial, Arial;
        font-weight: bold;
        font-size: 18px;
        color: #3C485B;
        line-height: 21px;
        border: 1px solid transparent;
    }

    .selected {
        border-radius: 6px;
        background: #FFFFFF;
        box-shadow: 0px 2px 10px 0px #CED6DD;
        color: #D31017;
        border: 1px solid #D31017;
    }

    .content {
        width: 100%;
        display: flex;

      & > div {
        align-self: stretch;
      }

        .card {
            background: #FFFFFF;
            box-shadow: 0px 2px 10px 0px #CED6DD;
            border-radius: 6px;
            padding: 20px;
        }

        .card-title {
            font-family: Arial, Arial;
            font-size: 16px;
            font-weight: bold;
            color: rgba(0, 0, 0, 0.85);
            line-height: 18px;
        }

        .card-base {
            width: 53.5vw;
        }

        .card-height {
            max-height: 1292px;
        }

        .card-mini {
            width: 43vw;
            max-height: 430px;
        }

        .card-full {
            width: 97.6vw;
        }

      .follow-list {
        .title-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
      }
    }

    .item-size {
        width: 14px;
        height: 14px;
        margin-right: 6px;
    }
}
</style>
