<template>
  <div v-loading="pageLoading" class="app-container">
    <card-table :loading="loading" :modalData="historyList" :searchParams="queryParams"
                :tableSearch="true" labelWidth="120px" @columnSearch="handleQuery" @pagination="getList" :max-height="$store.getters.tableMaxHeight"
                @selection-change="handleSelectionChange" @resetList="resetQuery" @sortChange="sortChange" show-no show-selection>
      <template #operations="{ selections }">
        <el-button v-hasPermi="['user:tcAgentHistory:export']" icon="el-icon-download" size="mini" plain
                   @click="handleExport">{{ $t('common.export') }}
        </el-button>
      </template>
      <template #default="{ list }">
        <!--代理商编号-->
        <Column :label="$t('agent.agentNo')" :searchParams="queryParams" show-search fixed prop="agentNo" sortable="custom">
          <template #default="{ row }">
            <span @click="handleView(row)" class="link-type">{{ row.agentNo }}</span>
          </template>
        </Column>
        <!--代理商名称-->
        <Column :label="$t('agent.agentName')" :searchParams="queryParams" :showSearch="true" prop="agentName" fixed />
        <!--所属区域-->
        <Column v-if="showAreaColumn" :label="$t('agent.area')" :labelProp="'areaName' + localLabelSuffix" :searchDict="areaOptions"
                :searchParams="queryParams" select-prop="areaIds"
                :showSearch="true" prop="areaId" searchType="select" selectMore valueProp="areaId">
          <template #default="{ row }">
            <span>{{ getAgentName(row.areaId) }}</span>
          </template>
        </Column>

        <!--创建时间-->
        <Column :label="$t('agent.changeTime')" :searchParams="queryParams" :showSearch="true" prop="createTime"
                searchType="dateRange"  prop-start="beginTime" prop-end="endTime"  width="300px">

        </Column>

        <Column :label="$t('agent.modifier')" :searchParams="queryParams" :showSearch="true" prop="createName" width="300px">

        </Column>


<!--        &lt;!&ndash; 是否签约 &ndash;&gt;-->
<!--        <Column :label="$t('agent.hasContract')" prop="hasContract" :searchDict="dict.type.yes_no_tinyint"-->
<!--                :searchParams="queryParams" :showSearch="true" searchType="select">-->
<!--        </Column>-->

<!--        &lt;!&ndash;上级代理&ndash;&gt;-->
<!--        <Column :label="$t('agent.parentAgent')" prop="parentAgentName" show-search :searchParams="queryParams">-->
<!--          <template #default="{ row }">-->
<!--            <span>{{ row.parentAgentId === 0 ? '-' : row.parentAgentName }}</span>-->
<!--          </template>-->
<!--        </Column>-->

<!--        &lt;!&ndash;上级销售&ndash;&gt;-->
<!--        <Column :label="$t('agent.parentSaler')" prop="parentSalerName" show-search :searchParams="queryParams">-->
<!--          <template #default="{ row }">-->
<!--            <span>{{ row.parentSalerId ? row.parentSalerName : '-' }}</span>-->
<!--          </template>-->
<!--        </Column>-->

<!--        &lt;!&ndash;代理商等级&ndash;&gt;-->
<!--        <Column :label="$t('agent.agentLevel')" :searchDict="dict.type.agent_level" :searchParams="queryParams"-->
<!--                :showSearch="true" prop="agentLevel" sortable="custom" selectProp="agentLevels"-->
<!--                searchType="select" selectMore>-->
<!--          <template #default="{ row }">-->
<!--            <span>{{ row.agentLevelName }}</span>-->
<!--          </template>-->
<!--        </Column>-->

<!--        &lt;!&ndash;授权区域&ndash;&gt;-->
<!--        <Column :label="$t('agent.authorizedArea')" prop="authorizedArea" width="250" show-search :searchParams="queryParams"/>-->

<!--        &lt;!&ndash;城市&ndash;&gt;-->
<!--        <Column :label="$t('project.city')" prop="city" show-search :searchParams="queryParams"/>-->

<!--        &lt;!&ndash;折扣率  v-hasRole="['system_manager', 'sales_director']" &ndash;&gt;-->
<!--        <Column v-if="checkRole(['admin', 'system_manager', 'sales_director'])" :label="$t('agent.discountRate') + '(%)'" prop="discount"/>-->

<!--        &lt;!&ndash;联系方式&ndash;&gt;-->
<!--        <Column :label="$t('agent.phone')" prop="phone" show-search :searchParams="queryParams"/>-->

<!--        &lt;!&ndash;首次合作年份&ndash;&gt;-->
<!--        <Column :label="$t('project.beginYear')" prop="firstCooperationYear" show-search :searchParams="queryParams"-->
<!--                search-type="dateRange" date-type="year"/>-->

<!--        &lt;!&ndash;来源&ndash;&gt;-->
<!--        <Column :label="$t('lead.origin')" :searchDict="dict.type.lead_source" :showSearch="true" prop="origin" selectProp="origins"-->
<!--                searchType="select" selectMore :searchParams="queryParams"/>-->

<!--        &lt;!&ndash; 协议生效日期&ndash;&gt;-->
<!--        <Column :label="$t('agent.protocolStartDate')" prop="protocolStartDate" show-search :searchParams="queryParams"-->
<!--                search-type="dateRange" prop-start="protocolSsDate" prop-end="protocolSeDate" width="250"/>-->
<!--        &lt;!&ndash; 协议失效日期&ndash;&gt;-->
<!--        <Column :label="$t('agent.protocolEndDate')" prop="protocolEndDate" show-search :searchParams="queryParams"-->
<!--                search-type="dateRange" prop-start="protocolEsDate" prop-end="protocolEeDate" width="250"/>-->


        <!--国家-->
<!--        <Column :label="$t('account.country')" :search-dict="curCountryOps" :showSearch="true" label-prop="second"-->
<!--                prop="countryId"-->
<!--                search-type="select" select-more value-prop="first" select-prop="countries"-->
<!--        >-->
<!--          <template #default="{ row }">-->
<!--            <span>{{ row.countryName }}</span>-->
<!--          </template>-->
<!--        </Column>-->

        <Column :label="$t('common.operate')" :min-width="180" :showSearch="true" fixed="right" searchType="operate"></Column>
      </template>
    </card-table>

    <!-- 添加或修改对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" append-to-body
               custom-class="edit-dialog" width="40vw"
    >
      <el-form ref="form" :model="form" :rules="rules" label-position="top" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="12">
            <!-- 代理商名称-->
            <el-form-item :label="$t('agent.agentName')" prop="agentName">
              <el-input v-model="form.agentName" :placeholder="$t('common.pleaseInput') + $t('agent.agentName')"
                        :disabled="readOnly" maxlength="100"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <!-- 代理商等级-->
            <el-form-item :label="$t('agent.agentLevel')" prop="agentLevel">
              <el-select v-model="form.agentLevel" :placeholder="$t('common.pleaseSelect') + $t('agent.agentLevel')"
                         :disabled="readOnly" class="w-100" clearable>
                <el-option v-for="dict in dict.type.agent_level" :key="dict.value" :label="dict.label"
                           :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item :label="$t('agent.area')" prop="areaId">
              <treeselect v-model="form.areaId" :options="areaTree" :placeholder="$t('user.placeholder_area')" :disabled="readOnly"
                          :noResultsText="$t('common.noResultsText')" :show-count="true" @input="clearArea" @select="areaChange">
                <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 :data="countryOptions" :label="$t('nation.countryName')" multiple :collapse-tags="false" required :disabled="readOnly"
                    prop="countryIds" width="100%" clearable :label-prop="'countryName' + localLabelSuffix" value-prop="countryId"/>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <!-- 城市-->
          <el-col :span="12">
            <!--<Input :label="$t('nation.cityName')" prop="cityName" width="100%"/>-->
            <Input prop="city" :label="$t('project.city')" width="100%" :maxlength="30" required :disabled="readOnly"/>
          </el-col>

          <el-col :span="12">
            <!-- 负责人名称-->
            <el-form-item :label="$t('agent.head')" prop="head">
              <el-input v-model="form.head" :placeholder="$t('common.pleaseInput') + $t('agent.head')"
                        :disabled="readOnly" maxlength="50"/>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <!--代理商类型-->
            <el-form-item :label="$t('agent.type')" prop="agentType">
              <el-select v-model="form.agentType" :placeholder="$t('common.pleaseSelect') + $t('agent.type')"
                         class="w-100" clearable @change="agentTypeChange" :disabled="readOnly">
                <el-option v-for="dict in dict.type.agent_type" :key="dict.value" :label="dict.label"
                           :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <!-- 上级代理，没有则为0-->
            <el-form-item v-if="form.agentType === '2'" :label="$t('agent.parentAgent')" prop="parentAgentId">
              <el-select v-model="form.parentAgentId" :placeholder="$t('common.pleaseSelect') + $t('agent.parentAgent')"
                         class="w-100" clearable :disabled="readOnly">
                <el-option v-for="item in agentOptions" :key="item.agentId" :label="item.agentName"
                           :value="item.agentId"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <!-- 上级销售ID userId-->
            <!--            <el-form-item v-if="form.agentType === '1'" :label="$t('agent.parentSaler')" prop="parentSalerId">-->
            <el-form-item :label="$t('agent.parentSaler')" prop="parentSalerId">
              <el-select v-model="form.parentSalerId" :placeholder="$t('common.pleaseSelect') + $t('agent.parentSaler')"
                         class="w-100" clearable :disabled="readOnly">
                <el-option v-for="item in salesOptions" :key="item.userId" :label="item.nickName"
                           :value="item.userId"/>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col v-if="checkRole(['admin', 'system_manager', 'sales_director'])" :span="12">
            <InputNumber :label="$t('agent.discountRate') + '(%)'" :max="100" :min="0" :precision=2 prop="discount"
                         required :disabled="readOnly"
                         width="100%"/>
          </el-col>
          <!-- 来源 -->
          <el-col :span="12">
            <Select v-model="form.origin" :data="dict.type.lead_source" :disabled="readOnly"
                    :label="$t('lead.origin')" prop="origin" width="100%"
            />
          </el-col>

          <el-col :span="12">
            <!-- 联系方式-->
            <el-form-item :label="$t('agent.phone')" prop="phone">
              <el-input v-model="form.phone" :placeholder="$t('common.pleaseInput') + $t('agent.phone')"
                        :disabled="readOnly" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 邮箱-->
            <el-form-item :label="$t('agent.email')" prop="email">
              <el-input v-model="form.email" :placeholder="$t('common.pleaseInput') + $t('agent.email')"
                        :disabled="readOnly" maxlength="100"/>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <!-- 是否签约 -->
            <el-form-item :label="$t('agent.hasContract')" prop="hasContract">
              <!--<el-radio v-model="form.hasContract" :label="true">{{ $t('common.yes') }}</el-radio>-->
              <!--<el-radio v-model="form.hasContract" :label="false">{{ $t('common.no') }}</el-radio>-->
              <!--              <div style="display: flex;width: 98%">-->
              <!--                <el-radio v-model="form.hasContract" v-for="yn in dict.type.yes_no_tinyint" :key="yn.value" style="width: 100%"-->
              <!--                          :label="Number(yn.value)">{{ yn.label }}-->
              <!--                </el-radio>-->
              <!--              </div>-->

              <el-select v-model="form.hasContract" :placeholder="$t('common.pleaseSelect')" style="width: 100%" :disabled="readOnly" >
                <el-option
                  v-for="item in dict.type.yes_no_tinyint"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(item.value)">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>


          <!--首次合作年份-->
          <el-col :span="12">
            <DatePicker :label="$t('project.beginYear')" prop="firstCooperationYear" type="year" width="100%" :disabled="readOnly" />
          </el-col>

          <el-col :span="12">
            <!-- 协议生效日期 -->
            <DatePicker :label="$t('agent.protocolStartDate')" :max-time="form.protocolEndDate" :mini-able="false"
                        :required="!!form.hasContract" prop="protocolStartDate" width="100%" :disabled="readOnly" />
          </el-col>
          <!--协议失效日期-->
          <el-col :span="12">
            <DatePicker :label="$t('agent.protocolEndDate')" :mini-time="form.protocolStartDate" :max-able="false"
                        :required="!!form.hasContract" prop="protocolEndDate" width="100%" :disabled="readOnly" />
          </el-col>


        </el-row>

        <el-row>
          <!-- 授权区域（textarea） -->
          <el-col :span="24">
            <Input type="textarea" :label="$t('agent.authorizedArea')" prop="authorizedArea" width="100%"
                   :maxlength="500" :disabled="readOnly" />
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="24">
            <!-- 地址-->
            <el-form-item :label="$t('agent.adder')" prop="address">
              <el-input v-model="form.address" :placeholder="$t('common.pleaseInput') + $t('agent.adder')"
                        :disabled="readOnly" maxlength="255"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <!-- 备注-->
            <el-form-item :label="$t('common.remark')" prop="remark">
              <el-input v-model="form.remark" :placeholder="$t('common.pleaseInput') + $t('common.remark')"
                        :disabled="readOnly" maxlength="500" show-word-limit type="textarea"/>
            </el-form-item>
          </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="readOnly" :fileType="[]" :isShowTip="false"
              >
              </FileUpload>

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

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button v-if="!readOnly" 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>

  </div>
</template>

<script>

import {getHistory, listHistory} from "@/api/user/history";
import tcAgentHistory from "@/views/user/tcAgentHistory/index.vue";
import Column from "@/components/element/table/Column.vue";
import {checkRole} from "@/utils/permission";
import {getAgent, getAgentByAreaId, getArea, getCountryByAreaId, getSalesByAreaId} from "@/api/user/agent";
import {getAreaTreeByUser} from "@/api/common/common";
import {getCountryList} from "@/api/business/crm/follow";
import DatePicker from "@/components/element/form/items/DatePicker.vue";
import InputNumber from "@/components/element/form/items/InputNumber.vue";
import Treeselect from "@riophae/vue-treeselect";
import FileUpload from "@/components/FileUpload/index.vue";

export default {
  name: "History",
  props: {
    placeholder: {type: String, default: '默认占位符'}
  },
  components: {DatePicker, InputNumber, Treeselect, Column, FileUpload},
  dicts: ['sys_normal_disable', 'agent_type', 'agent_level', 'yes_no_tinyint', 'lead_source', 'yes_no_tinyint', 'currency_type'],
  computed: {
    tcAgentHistory() {
      return tcAgentHistory
    },
    localLabelSuffix() {
      return localStorage.getItem('labelSuffix') || '';
    },

    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));
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      pageLoading: false,
      targetLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 代理商档案表格数据
      historyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        agentId: null,
        agentNo: null,
        agentName: null,
        areaId: null,
        countryId: null,
        city: null,
        agentType: null,
        hasContract: null,
        parentAgentId: null,
        parentSalerId: null,
        agentLevel: null,
        discount: null,
        head: null,
        phone: null,
        email: null,
        address: null,
        status: null,
        permissionChar: null,
        origin: null,
        firstCooperationYear: null,
        protocolStartDate: null,
        protocolEndDate: null,
        authorizedArea: null
      },
      curCountryOps: [],
      // 表单参数
      form: {},
      assessForm: {},
      // 国家选项
      countryOptions: [],
      // 区域tree
      areaTree: [],
      // 区域选项
      areaOptions: [],
      // 快速查询
      areaMap: new Map(),
      // 上级销售选项
      salesOptions: [],
      // 上级代理选项
      agentOptions: [],
      // 表单校验
      rules: {
        agentId: [
          { required: true, message: "代理商ID不能为空", trigger: "blur" }
        ],
      },
      readOnly:true
    };
  },
  created() {
    this.getArea();
    this.getList();
    this.curCountry()
  },
  methods: {
    /** 查询代理商档案列表 */
    async getList() {
      this.loading = true;
      const {createTime, protocolStartDate, protocolEndDate, ...params} = this.queryParams;
      // 如果有区域，并且有值
      if (params.areaId) {
        // params.areaIds = params.areaId;
        delete params.areaId;
      }
      if (params.agentLevel) {
        // params.agentLevels = params.agentLevel;
        delete params.agentLevel;
      }
      // 如果存在origin
      if (params.origin) {
        delete params.origin;
      }
      if (this.queryParams.firstCooperationYear) {
        // params.firstCooperationYear = this.$moment(this.queryParams.firstCooperationYear).format('YYYY-MM-DD HH:mm:ss')
        params.firstCooperationYear = this.$moment(this.queryParams.firstCooperationYear).format('YYYY')
      }

      try {
        const response = await listHistory(params);
        this.historyList = response.rows;
        this.queryParams.total = response.total;
        this.historyList.forEach(item => {
          item.agentLevelName = this.dict.label.agent_level[item.agentLevel];
          item.agentTypeName = this.dict.label.agent_type[item.agentType];
          item.isThisYear = this.isThisYear(item);
        });
      } finally {
        this.loading = false;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.$set(this.form, 'agentId', null)
      this.$set(this.form, 'id', null)
      this.$set(this.form, 'agentNo', null)
      this.$set(this.form, 'agentName', null)
      this.$set(this.form, 'areaId', null)
      this.$set(this.form, 'countryId', null)
      this.$set(this.form, 'city', null)
      this.$set(this.form, 'agentType', null)
      this.$set(this.form, 'hasContract', null)
      this.$set(this.form, 'parentAgentId', null)
      this.$set(this.form, 'parentSalerId', null)
      this.$set(this.form, 'agentLevel', null)
      this.$set(this.form, 'discount', null)
      this.$set(this.form, 'head', null)
      this.$set(this.form, 'phone', null)
      this.$set(this.form, 'email', null)
      this.$set(this.form, 'address', null)
      this.$set(this.form, 'status', null)
      this.$set(this.form, 'permissionChar', null)
      this.$set(this.form, 'delFlag', null)
      this.$set(this.form, 'createTime', null)
      this.$set(this.form, 'createBy', null)
      this.$set(this.form, 'updateTime', null)
      this.$set(this.form, 'updateBy', null)
      this.$set(this.form, 'remark', null)
      this.$set(this.form, 'origin', null)
      this.$set(this.form, 'firstCooperationYear', null)
      this.$set(this.form, 'protocolStartDate', null)
      this.$set(this.form, 'protocolEndDate', null)
      this.$set(this.form, 'authorizedArea', null)
      this.$set(this.form, 'parentAgentName', null)
      //this.resetForm("form");
      this.areaTree = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$set(this.queryParams, 'agentId', null)
      this.$set(this.queryParams, 'agentNo', null)
      this.$set(this.queryParams, 'agentName', null)
      this.$set(this.queryParams, 'areaId', null)
      this.$set(this.queryParams, 'countryId', null)
      this.$set(this.queryParams, 'city', null)
      this.$set(this.queryParams, 'agentType', null)
      this.$set(this.queryParams, 'hasContract', null)
      this.$set(this.queryParams, 'parentAgentId', null)
      this.$set(this.queryParams, 'parentSalerId', null)
      this.$set(this.queryParams, 'agentLevel', null)
      this.$set(this.queryParams, 'discount', null)
      this.$set(this.queryParams, 'head', null)
      this.$set(this.queryParams, 'phone', null)
      this.$set(this.queryParams, 'email', null)
      this.$set(this.queryParams, 'address', null)
      this.$set(this.queryParams, 'status', null)
      this.$set(this.queryParams, 'permissionChar', null)
      this.$set(this.queryParams, 'origin', null)
      this.$set(this.queryParams, 'firstCooperationYear', null)
      this.$set(this.queryParams, 'protocolStartDate', null)
      this.$set(this.queryParams, 'protocolEndDate', null)
      this.$set(this.queryParams, 'authorizedArea', null)

      this.$set(this.queryParams, 'protocolSsDate', null);
      this.$set(this.queryParams, 'protocolSeDate', null);
      this.$set(this.queryParams, 'protocolEsDate', null);
      this.$set(this.queryParams, 'protocolEeDate', null);

      this.$set(this.queryParams, 'areaIds', null)
      this.$set(this.queryParams, 'parentAgentName', null)
      this.$set(this.queryParams, 'parentSalerName', null)
      this.$set(this.queryParams, 'agentLevels', null)
      this.$set(this.queryParams, 'origins', null)

      this.$set(this.queryParams, 'beginTime', null)
      this.$set(this.queryParams, 'endTime', null)

      this.$set(this.queryParams, 'createName', null)

      this.handleQuery();
    },




    /** 导出按钮操作 */
    handleExport() {
      this.download('system/history/export', {
        ...this.queryParams
      }, `history_${new Date().getTime()}.xlsx`)
    },

    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();
    },
    getAgentName(areaId) {
      if (areaId !== null && areaId !== undefined && areaId >= 0) {
        const area = this.areaMap.get(areaId);
        if (area) {
          return area['areaName' + this.localLabelSuffix]
        }
      }
      return '-'
    },
    checkRole,

    // 下拉
    async getArea() {
      try {
        const response = await getArea();
        this.areaOptions = response.data;
        this.areaMap = response.data.reduce((map, obj) => {
          map.set(obj.areaId, obj);
          return map;
        }, new Map());
      } catch (e) {
      }
    },
    // tree
    async getAreaTree() {
      const response = await getAreaTreeByUser()
      this.areaTree = response.data
      // console.log('allAreaList', this.areaTree)
      // 如果存在全球根节点（id=0），则排除根节点
      this.areaTree = this.areaTree.filter(item => item.id !== 0)

    },
    //获取国家
    async curCountry() {
      const response = await getCountryList()
      this.curCountryOps = response.data
    },
    isThisYear(row) {
      if (row.agentTarget && row.agentTarget.targetYear) {
        if (new Date().getFullYear() === this.$moment(row.agentTarget.targetYear).year()) {
          return 1
        } else {
          return 0
        }
      }
    },
    /** 查看按钮操作 */
    async handleView(row) {
      // this.$tab.openPage(this.$t('project.view'), '/project-view/' + row.projectId);
      this.readOnly = true;
      this.pageLoading = true;
      try {
        this.reset();
        //const agentId = row.id
        await this.getAreaTree();
        const response = await getHistory(row.id );
        this.form = response.data;
        this.form.countryIds = !!this.form.countryId ? this.form.countryId.split(',').map(id => parseInt(id, 10)) : [];
        // 根据区域id查询国家
        console.log('response:', response)
        await Promise.all([
          this.getCountryByAreaId(response.data.areaId),
          this.handleQueryByType(response.data.agentType, response.data.areaId)
        ]);
        this.open = true;
        this.title = this.$t('common.view') + this.$t('agent.agentResume');
      } finally {
        this.pageLoading = false;
      }
    },
    clearArea(val) {
      if (!val) {
        this.$set(this.form, "parentSalerId", '');
        this.$set(this.form, "parentAgentId", '');
        this.$set(this.form, "countryIds", null);
        this.salesOptions = [];
        this.agentOptions = [];
        this.countryOptions = [];
      }
      this.$refs.form.validateField('areaId');

    },
    areaChange(val) {
      // 为空时清空上级区域
      this.$set(this.form, "countryIds", null);
      if (this.form.agentType === '1') {
        this.$set(this.form, "parentSalerId", '');
      } else {
        this.$set(this.form, "parentAgentId", '');
      }
      if (val.id) {
        this.getCountryByAreaId(val.id)
        this.handleQueryByType("1", val.id)
        this.handleQueryByType("2", val.id)
      }
    },

    agentTypeChange(val) {
      this.$set(this.form, "parentAgentId", '');
      this.$set(this.form, "parentSalerId", '');
      const areaId = this.form.areaId;
      if (areaId || areaId === 0) {
        this.handleQueryByType(val, this.form.areaId);
        if(val === '2'){
          this.handleQueryByType('1', this.form.areaId);
        }
      }

      this.$refs.form.clearValidate('parentAgentId');
      this.$refs.form.clearValidate('parentSalerId');

    },
    async getCountryByAreaId(areaId) {
      const response = await getCountryByAreaId(areaId);
      console.log("countryOptions=============>",response)
      this.$set(this, 'countryOptions', response.data);
    },
    async handleQueryByType(type, areaId) {
      if (type) {
        if (type === '1') {
          await this.getSalesByAreaId(areaId);
        } else if (type === '2') {
          await this.getSalesByAreaId(areaId);
          await this.getAgentByAreaId(areaId);
        }
      }
    },
    // 获取销售人员列表
    async getSalesByAreaId(areaId) {
      if (areaId !== null && areaId !== undefined && areaId >= 0) {
        const resp = await getSalesByAreaId(areaId);
        this.salesOptions = resp.data;
      } else {
        // 提示 TODO 使用 表单校验提示
        this.$message.error('area is empty');
      }
    },

    // 根据地区id获取代理商列表
    async getAgentByAreaId(areaId) {
      if (areaId !== null && areaId !== undefined && areaId >= 0) {
        const resp = await getAgentByAreaId(areaId, this.form.agentId);
        this.agentOptions = resp.data;
      } else {
        // 提示 TODO 使用 表单校验提示
        this.$message.error('area is empty');
      }
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

  }
};
</script>


<style lang="scss" scoped>
::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;
  }
}
</style>

