<template>
  <div class="app-container">
    <card-table :modalData="accountList" labelWidth="120px" :searchParams="queryParams" @pagination="getList"
                @selection-change="handleSelectionChange" :loading="loading" :tableSearch="true" @columnSearch="handleQuery"
                @resetList="resetQuery" @sortChange="sortChange" :max-height="$store.getters.tableMaxHeight" show-no show-selection
    >
      <template #operations="{ selections }">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                     v-hasPermi="['business:account:add']">{{ $t('account.add') }}
          </el-button>
        </el-col>
        <el-col :span="1.5" style="margin-left: 10px;">
          <el-button :disabled="!canMerge" type="primary" icon="el-icon-edit" size="mini" @click="handleMerge"
                     v-hasPermi="['business:account:merge']">{{
              $t('account.merge')
            }}
          </el-button>
        </el-col>
        <el-col :span="1.5" style="margin-left: 10px;">
          <ImportModal :title="$t('common.import')" icon="el-icon-upload2" fileName="客户信息导入模板" :table-type="1"
                       :close="getList"></ImportModal>
        </el-col>
        <el-col :span="1.5" style="margin-left: 10px;">
          <el-button plain icon="el-icon-download" size="mini" @click="handleExport"
                     v-hasPermi="['business:account:export']">{{ $t('common.export') }}
          </el-button>
        </el-col>
      </template>
      <template #default="{ list }">
        <!--<el-table-column type="selection" width="55" align="center" />-->
        <!--<el-table-column label="No." type="index" width="50" align="center" fixed />-->
        <!-- 客户编码 -->
        <Column :label="$t('account.accountNo')" prop="accountNo" :searchParams="queryParams" :showSearch="true"
                fixed width="200px" sortable="custom">
          <template #default="{ row }">
            <span @click="handleView(row)" class="link-type">{{ row.accountNo }}</span>
          </template>
        </Column>
        <!-- 公司名称 -->
        <Column :label="$t('account.accountName')" prop="accountName" :searchParams="queryParams" fixed
                :showSearch="true" width="250px"/>
        <!-- 区域 -->
        <Column v-if="showAreaColumn" :label="$t('user.area')" prop="areaId" :searchParams="queryParams"
                :searchDict="areaList" :showSearch="true" valueProp="first"
                labelProp="second" searchType="select" selectMore width="200px"/>
        <!-- 国家 -->
        <Column :label="$t('account.country')" prop="countryId" :searchParams="queryParams" :showSearch="true"
                valueProp="first" labelProp="second" searchType="select"
                :searchDict="nationList" select-more width="200px"/>
        <!--城市-->
        <Column :label="$t('project.city')" prop="city" width="200px" show-search :searchParams="queryParams" />

        <!-- 所属代理商 -->
        <Column :label="$t('lead.agent')" prop="ownerAgent" :showSearch="true" search-type="select"
                :searchParams="queryParams" :search-dict="agentList" select-more value-prop="agentId"
                label-prop="agentName" width="250px">
          <template #default="{ row }">
                        <span>{{
                            row.ownerAgentName == 'common.head' ? $t(row.ownerAgentName) :
                              row.ownerAgentName
                          }}</span>
          </template>
        </Column>
        <!--&lt;!&ndash; 客户类型 &ndash;&gt;-->
        <!--<Column :label="$t('account.type')" prop="type" :searchParams="queryParams" :showSearch="true"-->
        <!--    searchType="select" :searchDict="dict.type.account_type" select-more width="200px" />-->
        <!--客户等级-->
        <Column :label="$t('account.level')" prop="level" :searchParams="queryParams" :showSearch="true"
                searchType="select" :searchDict="dict.type.account_level" select-more width="200px"/>

        <!-- 跟进状态 -->
        <Column :label="$t('account.status')" prop="status" :searchParams="queryParams" :showSearch="true"
                searchType="select" :searchDict="dict.type.account_status" select-more width="200px"
                sortable="custom">
          <template #default="{ row }">
            <ColorDictTag v-if="row.status" :bgc="statusColorMap[row.status].bgc"
                          :label="formatDict(row.status, dict.type.account_status)"
                          :label-color="statusColorMap[row.status].color"/>
            <span v-else>-</span>
          </template>
        </Column>
        <!-- 产品意向 -->
        <Column :label="$t('account.intentionalProduct')" prop="intentionalProduct" :searchParams="queryParams"
                :showSearch="true" searchType="select" :searchDict="dict.type.intentional_product" select-more
                width="200px"/>
        <!-- 项目类型 -->
        <Column :label="$t('lead.segment')" prop="segment" :searchParams="queryParams" :showSearch="true"
                searchType="select" :searchDict="dict.type.project_type" select-more width="200px"/>
        <!-- 最新跟进结果 -->
        <Column :label="$t('account.followDesc')" prop="followDesc" width="250px"/>

        <!-- 负责人 -->
        <Column :label="$t('agent.head')" prop="ownerName" :showSearch="true" :searchParams="queryParams"
                width="200px"/>
        <!-- 备注 -->
        <Column :label="$t('common.remark')" prop="remark" width="250px"/>

        <!--&lt;!&ndash; 公司类型 &ndash;&gt;-->
        <!--<Column :label="$t('account.companyType')" prop="companyType" :searchParams="queryParams"-->
        <!--    :showSearch="true" searchType="select" :searchDict="dict.type.company_type" select-more-->
        <!--    width="200px" />-->


        <!--&lt;!&ndash; 最新跟进时间 &ndash;&gt;-->
        <!--<Column :label="$t('account.followTime')" prop="followTime" width="250px">-->
        <!--    <template #default="{ row }">-->
        <!--        <span>{{ row.followTime ? getLocalTime(row.followTime, 'YYYY-MM-DD') : '-' }}</span>-->
        <!--    </template>-->
        <!--</Column>-->
        <!--&lt;!&ndash; 跟进人 &ndash;&gt;-->
        <!--<Column :label="$t('account.followPerson')" prop="followPerson" width="200px" />-->


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


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

            <el-dropdown @command="(command) => handleCommand(command, row)" style="margin-left:5px"
                         v-hasPermi="['business:account:remove','business:account:view','business:account:addProject',]">
              <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 command="delete" v-if="hasPermission(row)">
                  <el-button size="mini" type="text" icon="el-icon-delete"
                             v-hasPermi="['business:account:remove']">
                    {{ $t('common.delete') }}
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item command="history">
                  <el-button size="mini" type="text" icon="el-icon-view"
                             v-hasPermi="['business:account:view']">
                    {{ $t('account.viewHistory') }}
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item command="addProject" v-if="hasPermission(row)">
                  <el-button size="mini" type="text" icon="el-icon-plus"
                             v-hasPermi="['business:account:addProject']">
                    {{ $t('project.addProject') }}
                  </el-button>
                </el-dropdown-item>
                &lt;!&ndash; 更改负责人 &ndash;&gt;
                <el-dropdown-item command="changeOwner">
                  <el-button size="mini" type="text" icon="el-icon-edit" v-if="canChangeOwner(row)"
                             v-hasPermi="['business:account:changeOwner']">
                    {{ $t('project.changeOwner') }}
                  </el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>-->

            <MoreBtn :handle-command="handleCommand" :row="row" :btns="[
              { label: $t('common.edit'), command: 'edit', icon: 'el-icon-edit', permi: 'business:account:edit' ,showAble: hasPermission(row) && canEdit(row),},
              { label: $t('project.follow'), command: 'follow', icon: 'el-icon-right', permi: 'business:account:follow', showAble: hasPermission(row),},
              { label: $t('common.delete'), command: 'delete', icon: 'el-icon-delete', permi: 'business:account:remove', showAble: hasPermission(row),},
              { label: $t('account.viewHistory'), command: 'history', icon: 'el-icon-view', permi: 'business:account:view', },
              { label: $t('project.addProject'), command: 'addProject', icon: 'el-icon-plus', permi: 'business:account:addProject', showAble: hasPermission(row),},
              { label: $t('project.changeOwner'), command: 'changeOwner', icon: 'el-icon-edit', permi: 'business:account:changeOwner', showAble: canChangeOwner(row),},
            ]"/>
          </template>
        </Column>
      </template>
    </card-table>

    <!-- 客户合并对话框 -->
    <el-dialog :title="$t('account.merge')" :visible.sync="open" width="850px" append-to-body
               :close-on-click-modal="false">
      <el-button style="margin-bottom: 20px;" @click="addRow" type="primary" plain icon="el-icon-plus"
                 size="mini">{{
          $t('common.addRow')
        }}
      </el-button>
      <el-table :data="mergeList" max-height="400px" border
                :header-cell-style="{ background: '#F4F6F8', color: '#92A2B5' }">
        <el-table-column type="index" label="No" width="50" align="center"></el-table-column>
        <el-table-column prop="accountId" :label="$t('account.account')">
          <template slot-scope="scope">
            <el-select style="width: 500px;" v-model="scope.row.accountId" filterable
                       :placeholder="$t('common.pleaseSelect') + $t('account.account')">
              <el-option v-for="item in accountOptions" :key="item.value" :label="item.label"
                         :value="item.value"/>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common.operate')" width="200px" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="deleteRow(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="submit">
          {{ $t('common.confirm') }}
        </el-button>
        <el-button @click="cancel" icon="el-icon-remove-outline">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>

    <!-- 更新履历对话框 -->
    <el-dialog :title="$t('account.history')" :visible.sync="historyOpen" width="800px" append-to-body>
      <el-table :data="historyList" max-height="500px" border
                :header-cell-style="{ background: '#F4F6F8', color: '#92A2B5' }">
        <el-table-column type="index" label="No" width="50" align="center"></el-table-column>
        <el-table-column prop="version" :label="$t('common.version')" align="center"
                         width="100"></el-table-column>
        <el-table-column prop="nickName" :label="$t('common.createBy') + '/' + $t('common.updateBy')"
                         align="center" width="200px"></el-table-column>
        <el-table-column prop="modifyRemark" :label="$t('project.modifyRemark')" align="center"
                         width="200px" show-overflow-tooltip ></el-table-column>
        <el-table-column prop="createTime" :label="$t('common.createTime')" align="center"
                         width="200px"></el-table-column>
        <el-table-column :label="$t('common.operate')" width="220px" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button @click="handleViewHistoryInfo(scope.row)" size="mini" type="text"
                       icon="el-icon-view">{{ $t('account.viewHistoryInfo') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination :total="historyTotal" :page.sync="historyQueryParams.pageNum"
                  :limit.sync="historyQueryParams.pageSize" @pagination="getHistoryList"/>
    </el-dialog>

    <FollowDialog ref="followDialog" @returnRow="getList"></FollowDialog>

    <ProjectDialog ref="projectForm" :title="$t('project.addProject')" :visible="projectOpen" :form="form"
                   @closeDialog="closeDialog">
    </ProjectDialog>

    <el-dialog :title="$t('project.changeOwner')" :visible.sync="changeOwnerOpen" width="500px" append-to-body
               :before-close="cancelChangeOwner" :close-on-click-modal="false">
      <el-form ref="changeOwnerForm" :model="changeOwnerForm" :rules="changeOwnerRules" label-position="top">
        <el-form-item :label="$t('lead.owner')" prop="owner">
          <el-select v-model="changeOwnerForm.owner" clearable filterable
                     :placeholder="$t('common.pleaseSelect') + $t('lead.owner')" style="width: 300px;">
            <el-option v-for="item in ownerList" :key="item.userId" :label="item.nickName" :value="item.userId"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitChangeOwner" icon="el-icon-circle-check" :loading="confirmLoading">
          {{ $t('common.confirm') }}
        </el-button>
        <el-button @click="cancelChangeOwner" icon="el-icon-circle-check">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listAccount, delAccount, mergeAccount, listAll, getCountryList, getAreaList, changeOwner} from '@/api/business/crm/account'
import {getAllAreaList} from "@/api/user/area";
import {getAllNationList} from "@/api/user/country";
import {listHistory} from "@/api/business/crm/accountHistory";
import {selectForAccount} from "@/api/user/agent";
import ImportModal from "@/components/ImportModal/index";
import ProjectDialog from "@/views/crmManagement/project/dialog";
import FollowDialog from "@/views/crmManagement/follow/FollowDialog";
import ColorDictTag from "@/views/crmManagement/lead/ColorDictTag/index";
import {getLocalTime} from "@/utils/data/dataUtils"
import {parseTime} from "@/utils/ruoyi";
import {getAllOwnerList, getAreaOwnerList, getOwnerList} from '@/api/system/user'
import MoreBtn from '@/components/MoreBtn/index.vue'

const statusColorMap = {
  // 意向挖掘
  1: {
    color: '#0DCCD7',
    bgc: 'rgba(13,204,215,0.12)'
  },
  // 静默
  2: {
    color: '#FFC500',
    bgc: 'rgba(255,200,12,0.12)'
  },
  // 无效
  3: {
    color: '#D71943',
    bgc: '#FAEDED'
  },
  // 转化线索
  4: {
    color: '#8B71FD',
    bgc: 'rgba(139,113,253,0.12)'
  },
  // 转化项目
  5: {
    color: '#FC5821',
    bgc: 'rgba(252, 88, 33, 0.12)'
  },
  // 丢失
  6: {
    color: '#FFC500',
    bgc: 'rgba(255,200,12,0.12)'
  },
  // 活跃
  7: {
    color: '#24CA5D',
    bgc: 'rgba(24,199,84,0.12)'
  },
  // 暂无意向
  8: {
    color: '#AD2BBF',
    bgc: 'rgba(163,32,181,0.12)'
  },
}

const labelSuffix = {
  chinese: '',
  english: 'US',
  russia: 'RU',
  spanish: 'ES',
}

export default {
  name: "Account",
  dicts: ['account_status', 'account_level', 'account_type', 'company_type', 'intentional_product', 'project_type'],
  components: { MoreBtn, ImportModal, FollowDialog, ColorDictTag, ProjectDialog},
  data() {
    return {
      statusColorMap: statusColorMap,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户表格数据
      accountList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        language: this.$i18n.locale,
        countryId: "",
        level: "",
        type: "",
        status: "",
        orderStatus: "",
        ownerAgents: "",
      },
      // 国家列表
      nationList: [],
      mergeList: [],
      accountOptions: [],
      historyOpen: false,
      historyList: [],
      historyTotal: 0,
      curAccountId: null,
      historyQueryParams: {
        pageNum: 1,
        pageSize: 10,
        accountId: null,
      },
      permissionChar: '',
      userInfo: {},
      canMerge: false,
      language: null,
      agentList: [],
      projectOpen: false,
      form: {},
      areaList: [],
      changeOwnerOpen: false,
      confirmLoading: false,
      changeOwnerForm: {},
      ownerList: [],
      changeOwnerRules: {
        owner: [
          {required: true, message: this.$t('common.pleaseSelect') + this.$t('project.owner'), trigger: "change"},
        ],
      },
    };
  },
  computed: {
    localLabelSuffix() {
      return labelSuffix[this.$i18n.locale] || '';
    },

    showAreaColumn() {
      // VP 、总经理
      // const allowedRoles = ["sales_director", "manager"];
      // return allowedRoles.some(role => this.$store.getters.roles.includes(role));
      // 不可见的角色： 区总、销售经理、代理商经理、代理商销售、销售支持 暂不考虑多角色比如又是销售又是vp角色
      const invisibleRoles = ['area_sales_director', 'sales_manager', 'agent_manager', 'agent_sales', 'sales_support'];
      return !this.$store.getters.roles.some(role => invisibleRoles.includes(role));
    }
  },
  created() {
    this.language = this.$i18n.locale;
    this.userInfo = this.$store.state.user.userInfo;
    this.permissionChar = this.$store.state.user.permissionChar
    this.getList();
    // this.getAreaList();
    // this.getNationList();
    this.getAgentList();
    // this.getOwnerList();

    this.$store.subscribe((mutation) => {
      if (mutation.type === 'getAccountList') {
        this.getList();
      }
    });

  },
  methods: {
    parseTime,
    getLocalTime,
    formatDict(value, dictData) {
      let data = dictData.find(dict => dict.value == value);
      if (data) {
        return data.label;
      } else {
        return '-';
      }
    },
    getAgentList() {
      selectForAccount().then(res => {
        this.agentList = res.data;
        if (this.userInfo.deptId == 0) {
          this.agentList.unshift({agentId: 0, agentName: this.$t('common.head')});
        }
      })
    },
    getAreaList() {
      getAreaList().then(res => {
        this.areaList = res.data;
      })
    },
    handleCommand(command, row) {
      switch (command) {
        case "edit":
          this.handleUpdate(row)
          break;
        case "delete":
          this.handleDelete(row)
          break;
        case "history":
          this.handleViewHistory(row)
          break;
        case "follow":
          this.handleFollow(row)
          break;
        case "addProject":
          this.handleAddProject(row)
          break;
        case "changeOwner":
          this.handleChangeOwner(row)
          break;
      }
    },
    /** 获取所有国家列表 */
    getNationList() {
      getCountryList().then(response => {
        this.nationList = response.data;
      })
    },
    /** 判断是否有权限 */
    hasPermission(row) {
      // let flag = true;
      //销售VP角色，可以任意操作
      return this.$store.getters.roles.includes('sales_director') || row.owner === this.$store.getters.userId;

      // let permissionArray = this.permissionChar.split(',');
      // let rowPermissionArray = row.permissionChar.split(',');
      // for (let i = 0; i < rowPermissionArray.length; i++) {
      //     if (!permissionArray.includes(rowPermissionArray[i])) {
      //         flag = false;
      //         break;
      //     }
      // }
      // return flag;
    },
    /** 当前用户是否可以编辑 */
    canEdit(row) {
      return true;
      // 获取角色权限字符数组
      // let roles = this.$store.state.user.roles
      // const allowedRoles = ['admin', 'manager', 'MKT', 'sales_director', 'sales_support', 'area_sales_director', 'sales_manager'];
      // if (allowedRoles.some(role => roles.includes(role))) {
      //     return true;
      // } else if (roles.includes('agent_manager')) {
      //     return row.ownerAgent == this.userInfo.deptId;
      // } else if (roles.includes('agent_sales')) {
      //     return row.owner == this.userInfo.userId;
      // } else {
      //     return false;
      // }
    },
    // canAddProject(row){
    //     return this.userInfo.userId == row.owner
    // },
    handleAddProject(row) {
      this.form = {
        accountId: row.accountId + "",
        accountNo: row.accountNo,
        accountName: row.accountName,
        areaId: row.areaId,
        countryId: row.countryId,
        owner: this.$store.getters.userId == 1 ? null : this.$store.getters.userId,
        ownerAgent: row.ownerAgent,
      }
      this.$refs.projectForm.defaultData = [{
        accountId: row.accountId,
        accountNo: row.accountNo,
        accountName: row.accountName,
        areaId: row.areaId,
        countryId: row.countryId,
      }]
      this.projectOpen = true;
      this.$refs.projectForm.getRelatedContact(this.form.accountId);
    },
    closeDialog() {
      this.projectOpen = false;
      this.getList();
    },
    /** 跟进 */
    handleFollow(row) {
      this.$refs.followDialog.dialogItemInit({flag: '1', accountId: row.accountId})
    },
    handleViewHistory(row) {
      this.historyQueryParams.pageNum = 1;
      this.curAccountId = row.accountId;
      this.getHistoryList();
      this.historyOpen = true;
    },
    handleViewHistoryInfo(row) {
      this.historyOpen = false;
      this.$tab.openPage(this.$t('account.view'), '/account-edit/index/' + row.accountId,
        {type: 'view', historyId: row.id});
    },
    getHistoryList() {
      // console.log('accountId', this.curAccountId)
      this.historyQueryParams.accountId = this.curAccountId;
      listHistory(this.historyQueryParams).then(response => {
        this.historyList = response.rows;
        this.historyTotal = response.total;
      })
    },
    /** 查询客户列表 */
    async getList() {
      this.loading = true;
      try {
        const res = await listAccount(this.queryParams)
        this.accountList = res.rows;
        this.queryParams.total = res.total;
      } finally {
        this.loading = false
      }

      // 由于改成了数据内存在的区域和国家，需要保持一致性，这里在每次查询的时候重新获取一次
      this.getAreaList();
      this.getNationList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        language: this.$i18n.locale,
        countryId: "",
        level: "",
        type: "",
        status: "",
        orderStatus: "",
        ownerAgents: "",
      }
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.accountId)
      this.canMerge = selection.length >= 2
      // 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();
    },

    /** 合并按钮操作 */
    handleMerge() {
      this.getAccountList();
      this.mergeList = [];
      if (this.ids.length > 0) {
        for (let i = 0; i < this.ids.length; i++) {
          this.mergeList.push({index: i + 1, accountId: this.ids[i]})
        }
      } else {
        this.mergeList = [{index: 1, accountId: null}, {index: 2, accountId: null}];
      }
      this.open = true;
    },
    getAccountList() {
      listAll({language: this.language}).then(response => {
        this.accountOptions = response.rows.map(item => {
          return {
            value: item.accountId,
            label: item.accountNo + ':' + '【' + item.accountName + ' - ' + item.areaName + ' - ' + item.countryName + '】'
          };
        });
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$tab.openPage(this.$t('account.add'), '/account-edit/index/0', {type: 'add'});
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$tab.openPage(this.$t('account.edit'), '/account-edit/index/' + row.accountId, {type: 'edit'});
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.$tab.openPage(this.$t('account.view'), '/account-edit/index/' + row.accountId, {type: 'view'});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const accountIds = row.accountId || this.ids;
      this.$modal.confirm(this.$t('common.isDelete')).then(function () {
        return delAccount(accountIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('common.deleteSuccess'));
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.queryParams.language = this.$i18n.locale;
      this.queryParams.ids = this.ids;
      let fileName = this.$t('index.guideOne') + parseTime(new Date(), '{y}{m}{d}') + '.xlsx'
      this.download('business/account/export', {
        ...this.queryParams
      }, fileName)
    },
    /** 导入按钮操作 */
    handleInport() {

    },
    /** 新增行 */
    addRow() {
      this.mergeList.push({index: this.mergeList.length + 1, accountId: null});
    },
    /** 删除行 */
    deleteRow(row) {
      this.mergeList = this.mergeList.filter(item => item.index != row.index);
      for (let i = 0; i < this.mergeList.length; i++) {
        this.mergeList[i].index = i + 1;
      }
    },
    cancel() {
      this.open = false;
    },
    submit() {
      let accountList = Object.assign([], this.mergeList);
      if (accountList.length < 2) {
        this.$modal.msgError(this.$t("account.mergeNumberMsg"));
        return;
      }
      if (accountList.findIndex(item => !item.accountId) > -1) {
        this.$modal.msgError(this.$t("account.mergeRequiredMsg"));
        return;
      }
      // 判断是否有重复客户
      let accountIdArray = accountList.map(item => item.accountId);
      if (new Set(accountIdArray).size !== accountIdArray.length) {
        this.$modal.msgError(this.$t("account.mergeDuplicateMsg"));
        return;
      }
      mergeAccount(accountList).then(response => {
        this.$modal.msgSuccess(this.$t('common.editSuccess'));
        this.open = false;
        this.getList();
      });
    },

    canChangeOwner(row) {
      return this.$store.state.user.userInfo.deptId === row.deptId || this.$store.getters.roles.includes('sales_director')
    },

    /** 更改负责人 */
    handleChangeOwner(row) {
      this.changeOwnerForm = {
        accountId: row.accountId,
        owner: row.owner,
        updateTime: row.updateTime
      }
      if (this.$store.getters.roles.includes('sales_director')) {
        getAllOwnerList({onlySalesRole: true}).then(res => {
          this.ownerList = res.data;
        })
      } else {
        this.listAreaOwnerList(row.areaId)
      }
      // this.listAreaOwnerList(row.areaId)
      this.changeOwnerOpen = true;
    },

    listAreaOwnerList(x) {
      let param = {areaId: x}
      getAreaOwnerList(param).then(res => {
        this.ownerList = res.data;
      })
    },

    cancelChangeOwner() {
      // this.resetForm("changeOwnerForm");
      this.changeOwnerOpen = false;
    },

    submitChangeOwner() {
      this.$refs["changeOwnerForm"].validate(valid => {
        if (valid) {
          this.confirmLoading = true;
          changeOwner(this.changeOwnerForm).then(response => {
            if (response.code == 200) {
              this.$modal.msgSuccess(this.$t('common.editSuccess'));
              this.changeOwnerOpen = false;
              this.getList();
            } else {
              this.$modal.msgError(response.msg);
            }
          }).catch(() => {
          });
          this.confirmLoading = false;
        }
      });
    },
  }
};
</script>
