<template>
  <div v-loading="pageLoading" class="app-container">
    <card-table :delProp="['createTime', 'origin']" :loading="loading" :modalData="agentList" :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:agent:add']" icon="el-icon-plus" size="mini" type="primary"
                   @click="handleAdd">{{ $t('agent.addAgent') }}
        </el-button>
        <el-button v-hasPermi="['user:agent:export']" icon="el-icon-download" size="mini" plain
                   @click="handleExport">{{ $t('common.export') }}
        </el-button>
      </template>
      <template #default="{ list }">
         <!--<el-table-column align="center" type="selection" width="55"/>-->
        <!--<el-table-column align="center" fixed label="No." type="index" width="50"/>-->
        <!--代理商编号-->
        <Column :label="$t('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.authorizedArea')" prop="authorizedArea" width="250" show-search :searchParams="queryParams"/>
        <!--城市-->
        <Column :label="$t('project.city')" prop="city" show-search :searchParams="queryParams"/>

        <!--类型 -->
        <Column :label="$t('agent.type')" :searchDict="dict.type.agent_type" :searchParams="queryParams"
                :showSearch="true" sortable="custom"
                prop="agentType" searchType="select">
          <template #default="{ row }">
            <span>{{ row.agentTypeName }}</span>
          </template>
        </Column>
        <!-- 是否签约 -->
        <Column :label="$t('agent.hasContract')" prop="hasContract" :searchDict="dict.type.yes_no_tinyint"
                :searchParams="queryParams" :showSearch="true" searchType="select">
        </Column>
        <!--上级代理-->
        <Column :label="$t('agent.parentAgent')" prop="parentAgentName" show-search :searchParams="queryParams">
          <template #default="{ row }">
            <span>{{ row.parentAgentId === 0 ? '-' : row.parentAgentName }}</span>
          </template>
        </Column>
        <!--上级销售-->
        <Column :label="$t('agent.parentSaler')" prop="parentSalerName" show-search :searchParams="queryParams">
          <template #default="{ row }">
            <span>{{ row.parentSalerId ? row.parentSalerName : '-' }}</span>
          </template>
        </Column>
        <!--代理商等级-->
        <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>

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

        <!--折扣率  v-hasRole="['system_manager', 'sales_director']" -->
        <Column v-if="checkPermi(['user:agent:discountRate'])" :label="$t('agent.discountRate') + '(%)'" prop="discount"/>
<!--        <Column v-if="checkRole(['admin', 'system_manager', 'sales_director'])" :label="$t('agent.discountRate') + '(%)'" prop="discount"/>-->
        <!--联系方式-->
        <Column :label="$t('agent.phone')" prop="phone" show-search :searchParams="queryParams"/>
        <!--本年度考核-->
        <Column :label="$t('agent.thisYearExamine')" prop="isThisYear" :searchParams="queryParams"
                :searchDict="dict.type.yes_no_tinyint" searchType="select" show-search />
        <!--目标销售额-->
        <Column :label="$t('agent.targetMoney')" prop="agentTarget.targetMoney" align="right">
          <template #default="{ row }">
            <span>{{ row.agentTarget ? toDecimal2(numFormat(row.agentTarget.targetMoney)) : '-' }}</span>
          </template>
        </Column>
        <!--目标台数-->
        <Column :label="$t('agent.targetCount')" prop="agentTarget.targetElevatorCount">
          <template #default="{ row }">
            <span>{{ row.agentTarget ? row.agentTarget.targetElevatorCount : '-' }}</span>
          </template>
        </Column>
        <!--目标项目数-->
        <Column :label="$t('agent.targetProject')" prop="agentTarget.targetProjectCount">
          <template #default="{ row }">
            <span>{{ row.agentTarget ? row.agentTarget.targetProjectCount : '-' }}</span>
          </template>
        </Column>
        <!--状态-->
        <Column :label="$t('agent.status')" :searchDict="dict.type.sys_normal_disable" :showSearch="true"
                prop="status" searchType="select">
          <template #default="{ row }">
            <!--<span>{{ row.status === "0" ? $t('common.enabled') : $t('common.disabled') }}</span>-->
            <el-switch
              v-model="row.status"
              active-value="0"
              inactive-value="1"
              @change="handleStatusChange(row)"
            ></el-switch>
          </template>
        </Column>
        <!--来源-->
        <Column :label="$t('lead.origin')" :searchDict="dict.type.lead_source" :showSearch="true" prop="origin" selectProp="origins"
                searchType="select" selectMore :searchParams="queryParams"/>

        <!-- 协议生效日期-->
        <Column :label="$t('agent.protocolStartDate')" prop="protocolStartDate" show-search :searchParams="queryParams"
                search-type="dateRange" prop-start="protocolSsDate" prop-end="protocolSeDate" width="250"/>
        <!-- 协议失效日期-->
        <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('common.createTime')" :searchParams="queryParams" :showSearch="true" prop="createTime"
                searchType="dateRange"  prop-start="beginTime" prop-end="endTime"  width="300px">
          <!--<template #default="{ row }">-->
          <!--  <span>{{ parseTime(row.createTime) }}</span>-->
          <!--  <span>{{ moment(backendDate).format('YYYY-MM-DD HH:mm:ss'); }}</span>-->
          <!--</template>-->
        </Column>
        <Column :label="$t('common.operate')" :min-width="360" :showSearch="true" fixed="right" searchType="operate">
          <template #default="{ row }">
            <!--编辑-->
            <el-button v-hasPermi="['user:agent:edit']" :disabled="row.agentId === 0" icon="el-icon-edit" size="mini"
                       type="text" @click="handleUpdate(row)">{{ $t('common.edit') }}
            </el-button>
            <!--删除-->
            <el-button v-hasPermi="['user:agent:del']" :disabled="row.agentId === 0" icon="el-icon-delete" size="mini"
                       type="text" @click="handleDelete(row)">{{ $t('common.delete') }}
            </el-button>
            <!--考核-->
            <el-button v-hasPermi="['user:agent:assess']" icon="el-icon-edit" size="mini" v-if="!isInPerson(row)"
                       type="text" @click="handleAssess(row)">{{ $t('agent.assess') }}
            </el-button>

            <!-- 下面是二期 ，在一期分支中暂时注掉 -->
            <!--<el-dropdown v-hasPermi="['user:agent:edit', 'user:agent:del']" size="mini"-->
            <!--             @command="(command) => handleCommand(command, row)">-->
            <!--  <el-button icon="el-icon-d-arrow-right" size="mini" type="text">{{ $t('common.more') }}</el-button>-->

            <!--  <el-dropdown-menu slot="dropdown">-->
            <!--    &lt;!&ndash;代理商考核&ndash;&gt;-->
            <!--    <el-dropdown-item v-hasPermi="['user:agent:assess']" command="handleAssess"-->
            <!--                      icon="el-icon-edit">{{ $t('agent.assess') }}-->
            <!--    </el-dropdown-item>-->
            <!--    &lt;!&ndash;删除&ndash;&gt;-->
            <!--    <el-dropdown-item v-hasPermi="['user:agent:del']" command="handleDelete"-->
            <!--                      icon="el-icon-delete">{{ $t('common.delete') }}-->
            <!--    </el-dropdown-item>-->
            <!--  </el-dropdown-menu>-->
            <!--</el-dropdown>-->
          </template>
        </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>

          <template v-if="checkPermi(['user:agent:discountRate'])">
            <el-col  :span="12">
              <Select v-model="form.discountFlag" :data="dict.type.yes_no_tinyint.map(item => ({ label: item.label, value: item.value == '1' }))" :disabled="readOnly"
                      :label="$t('是否总价折率')" prop="discountFlag" ></Select>
            </el-col>
            <el-col  :span="12">
              <Select :label="$t('折率类型')" prop="discountType" :data="dict.type.value_type" required :disabled="readOnly"
                @change="form.discount = undefined; form.discountFormulaTxt = undefined" />
            </el-col>
            <el-col :span="12">
              <InputNumber v-if="form.discountType === '1'" :label="$t('agent.discountRate') + '(%)'" :max="10000" :min="0" :precision=2 prop="discount"
                         required :disabled="readOnly"
                         width="100%"/>
              <Input v-else :label="$t('agent.discountRate') + '(%)'" prop="discountFormulaTxt" showFormula required :maxlength="5000" :disabled="readOnly" :optionParaSelection="optionParaSelection"  width="100%"/>
            </el-col>
          </template>
          <!-- 来源 -->
          <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" controllerUrl="/common/upload-agent"
              >
              </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>

    <!-- 添加或修改代理商考核对话框 -->
    <el-dialog :close-on-click-modal="false" :title="assessTitle" :visible.sync="assessOpen" append-to-body
               width="40vw">
      <el-form v-loading="targetLoading" ref="assessForm" :model="assessForm" label-position="top" label-width="80px">

        <el-row :gutter="24">
          <!--代理商名称-->
          <el-col :span="12">
            <Input :label="$t('agent.agentName')" disabled prop="agentName" width="100%"/>
          </el-col>
          <!--所属区域-->
          <el-col :span="12">

            <Select :data="areaOptions" :label="$t('agent.area')" disabled label-prop="areaName"
                    prop="areaId"
                    value-prop="areaId"/>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <!--类型-->
          <el-col :span="12">
            <Select :data="dict.type.agent_type" :label="$t('agent.type')" disabled prop="agentType"/>
          </el-col>
          <!--等级-->
          <el-col :span="12">
            <Select :data="dict.type.agent_level" :label="$t('agent.agentLevel')" disabled prop="agentLevel"/>
          </el-col>

        </el-row>

        <el-row :gutter="24">
          <!--上级销售-->
          <el-col :span="12">
            <Input :label="$t('agent.parentSaler')" disabled prop="parentSalerName" width="100%"/>
          </el-col>
          <!--上级代理-->
          <el-col :span="12">
            <Input :label="$t('agent.parentAgent')" disabled prop="parentAgentName" width="100%"/>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <!--考核年度-->
          <el-col :span="12">
            <DatePicker :label="$t('agent.targetYear')" prop="targetYear" type="year" width="100%" required @change="targetYearChange"/>
          </el-col>
          <!--目标台数-->
          <el-col :span="12">
            <InputNumber :label="$t('agent.targetElevatorCount')" prop="targetElevatorCount" width="100%" required/>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <!--目标金额-->
          <el-col :span="12">
            <InputNumber :label="$t('agent.targetMoney')" prop="targetMoney" width="100%" required/>
          </el-col>
          <!--标杆项目数-->
          <el-col :span="12">
            <InputNumber :label="$t('agent.targetProjectCount')" prop="targetProjectCount" width="100%" required/>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <!-- 币种 -->
          <el-col :span="12">
            <Select :data="dict.type.currency_type" :label="$t('project.currency')" prop="currency" required width="100%" />
          </el-col>
        </el-row>
      </el-form>

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

<script>
import {
  addAgent,
  changeAgentStatus,
  delAgent,
  getAgent,
  getAgentByAreaId,
  getArea,
  getAreaTree,
  getCountryByAreaId,
  getSalesByAreaId,
  listAgent,
  updateAgent,
} from "@/api/user/agent";
import { parseTime, trimFormFields } from '@/utils/ruoyi'
import Column from "@/components/element/table/Column.vue";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import InputNumber from "@/components/element/form/items/InputNumber";
import DatePicker from "@/components/element/form/items/DatePicker.vue";
import { addOrEdit, addTarget, getInfoByQuery, updateTarget } from '@/api/user/target'
import { getAreaTreeByUser } from '@/api/common/common'
import FileUpload from '@/components/FileUpload'
import { checkRole,checkPermi } from '@/utils/permission'

export default {
  name: "Agent",
  components: {DatePicker, InputNumber, Treeselect, Column, FileUpload},
  dicts: ['sys_normal_disable', 'agent_type', 'agent_level', 'yes_no_tinyint', 'lead_source',  'currency_type', 'value_type'],
  data() {
    return {
      // 遮罩层
      loading: false,
      pageLoading: false,
      targetLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      agentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      assessTitle: "",
      assessOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        agentNo: null,
        agentName: null,
        areaId: null,
        countryIds: [],
        agentType: '',
        parentAgentId: null,
        parentSalerId: null,
        agentLevel: null,
        discount: null,
        head: null,
        phone: null,
        email: null,
        address: null,
        status: '',
        parentAgentName: null,
        parentSalerName: null,
        permissionChar: null,
        firstCooperationYear: null,
        isThisYear: null,
        beginTime: null,
        endTime: null,
        protocolSsDate: null,
        protocolSeDate: null,
        protocolEsDate: null,
        protocolEeDate: null,
        authorizedArea: null,
        city:null,
        hasContract:null,
        origin:null,
        createTime : null,
        areaIds : null,
        agentLevels : null,
        origins : null,
        protocolStartDate : null,
        protocolEndDate : null,
      },
      // 表单参数
      form: {
        discountType: '1'
      },
      assessForm: {},
      // 国家选项
      countryOptions: [],
      // 区域tree
      areaTree: [],
      // 区域选项
      areaOptions: [],
      // 快速查询
      areaMap: new Map(),
      // 上级销售选项
      salesOptions: [],
      // 上级代理选项
      agentOptions: [],
      // 表单校验
      rules: {
        agentName: [{
          required: true,
          message: this.$t('common.pleaseInput') + this.$t('agent.agentName'),
          trigger: "blur"
        }],
        agentLevel: [{
          required: true,
          message: this.$t('common.pleaseSelect') + this.$t('agent.agentLevel'),
          trigger: "change"
        }],
        agentType: [{
          required: true,
          message: this.$t('common.pleaseSelect') + this.$t('agent.type'),
          trigger: "change"
        }],
        countryIds: [{required: true, message: this.$t('common.pleaseSelect') + this.$t('nation.countryName'), trigger: "change"}],
        areaId: [{required: true, message: this.$t('common.pleaseSelect') + this.$t('agent.area'), trigger: "change"}],
        city: [
          { required: true, message: this.$t('common.pleaseInput') + this.$t('project.city'), trigger: 'blur' },
        ],
        discount: [{
          required: true,
          message: this.$t('common.pleaseInput') + this.$t('agent.discountRate'),
          trigger: "blur"
        },
          // 必须是数字校验 最小值0 最大值100  this.$t('common.onlyNumber') +
          {type: 'number', min: 0, max: 100, message: this.$t('agent.discountRange'), trigger: "blur"},
        ],
        head: [{required: true, message: this.$t('common.pleaseInput') + this.$t('agent.head'), trigger: "blur"}],
        phone: [{required: true, message: this.$t('common.pleaseInput') + this.$t('agent.phone'), trigger: "blur"},
          // 至少5位数
          {min: 5, message: this.$t('common.atLeast') + 5 + this.$t('common.digits'), trigger: "blur"}
        ],
        // 邮箱格式
        email: [{type: 'email', message: this.$t('common.pleaseCorrect') + this.$t('agent.email'), trigger: "blur"}],
        // 是否签约
        hasContract: [{
          required: true,
          message: this.$t('common.pleaseSelect') + this.$t('agent.hasContract'),
          trigger: "change"
        }],
        address: [{
          required: true,
          message: this.$t('common.pleaseInput') + this.$t('agent.addressPh'),
          trigger: "blur"
        }],
        parentAgentId: [{
          required: true,
          message: this.$t('common.pleaseSelect') + this.$t('agent.parentAgent'),
          trigger: "change"
        }],
        parentSalerId: [{
          required: true,
          message: this.$t('common.pleaseSelect') + this.$t('agent.parentSaler'),
          trigger: "change"
        }],
      },
      // 用户信息
      userInfo: this.$store.state.user.userInfo,

      readOnly: false,
    };
  },
  created() {
    this.getArea();
    this.getList();
    // this.getAreaTree();
  },

  computed: {
    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));
    }
  },

  methods: {
    // 是否本人
    isInPerson(row) {
      return this.userInfo.agent && (this.userInfo.agent.agentId === row.agentId);
    },
    checkRole,
    checkPermi,
    parseTime,
    /** 查询代理商列表 */
    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;
      }

      console.log('this.queryParams', this.queryParams)
      console.log('params', params)
      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 listAgent(params);
        this.agentList = response.rows;
        this.queryParams.total = response.total;
        this.agentList.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;
      }
    },

    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 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');
      }
    },

    // 下拉
    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)

    },

    areaChange(val) {
      // 为空时清空上级区域
      this.$set(this.form, "countryIds", []);
      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)
      }
    },

    async getCountryByAreaId(areaId) {
      const response = await getCountryByAreaId(areaId);
      // this.countryOptions = response.data;
      this.$set(this, 'countryOptions', response.data);
    },

    clearArea(val) {
      if (!val) {
        this.$set(this.form, "parentSalerId", '');
        this.$set(this.form, "parentAgentId", '');
        this.$set(this.form, "countryIds", []);
        this.salesOptions = [];
        this.agentOptions = [];
        this.countryOptions = [];
      }
      this.$refs.form.validateField('areaId');

    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    assessCancel() {
      this.assessOpen = false;
    },
    // 表单重置
    reset() {
      this.form = {
        agentId: null,
        agentNo: null,
        agentName: null,
        areaId: null,
        countryIds: [],
        agentType: null,
        parentAgentId: null,
        parentSalerId: null,
        agentLevel: null,
        discount: null,
        head: null,
        phone: null,
        email: null,
        address: null,
        status: null,
        permissionChar: null,
        delFlag: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null
      };
      this.resetForm("form");
      this.countryOptions = [];
      this.areaTree = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {

      this.$set(this.queryParams, 'agentNo', null);
      this.$set(this.queryParams, 'agentName', null);
      this.$set(this.queryParams, 'areaId', null);
      this.$set(this.queryParams, 'agentType', null);
      this.$set(this.queryParams, 'agentLevel', null);
      this.$set(this.queryParams, 'status', null);
      this.$set(this.queryParams, 'createTime', null);
      this.$set(this.queryParams, 'beginTime', null);
      this.$set(this.queryParams, 'endTime', null);
      this.$set(this.queryParams, 'hasContract', null);
      this.$set(this.queryParams, 'areaIds', null);
      this.$set(this.queryParams, 'agentLevels', null);
      this.$set(this.queryParams, 'origins', null);
      this.$set(this.queryParams, 'origin', null);
      this.$set(this.queryParams, 'city', null);
      this.$set(this.queryParams, 'parentAgentName', null);
      this.$set(this.queryParams, 'parentSalerName', null);
      this.$set(this.queryParams, 'firstCooperationYear', null);
      this.$set(this.queryParams, 'phone', null);
      this.$set(this.queryParams, 'isThisYear', 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.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.agentId)
      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();
    },

    /** 新增按钮操作 */
    async handleAdd() {
      this.reset();
      this.title = this.$t('agent.addAgent');
      await this.getAreaTree();
      this.readOnly = false;
      this.open = true;
    },

    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleAssess":
          this.handleAssess(row);
          break;
        case "handleDelete":
          this.handleDelete(row);
          break;
        default:
          break;
      }
    },

    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.readOnly = false
      this.pageLoading = true;
      try {
        this.reset();
        const agentId = row.agentId || this.ids
        await this.getAreaTree();
        const response = await getAgent(agentId);
        this.form = response.data;
        this.$set(this.form, 'discountType', response.data.discountType || '1')
        // 根据区域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('agent.editAgent');
      } finally {
        this.pageLoading = false;
      }
    },

    /** 提交按钮 */
    submitForm() {
      trimFormFields(this.form, ['agentName', 'head', 'phone', 'email', 'address', 'remark']);

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.agentId != null) {
            updateAgent(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.editSuccess'));
              this.open = false;
              this.getList();
            });
          } else {
            addAgent(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.addSuccess'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 提交按钮 */
    submitAssessForm() {
      this.$refs["assessForm"].validate(async valid => {
        if (valid) {
          try {
            this.pageLoading = true;
            this.assessForm.targetYear = this.assessForm.targetYear ? this.assessForm.targetYear + '-01-01' : null;
            // const response = await addOrEdit(this.assessForm);
            if (this.assessForm.targetId) {
              await updateTarget(this.assessForm);
            } else {
              await addTarget(this.assessForm);
            }
            this.$modal.msgSuccess(this.assessForm.targetId ? this.$t('common.editSuccess') : this.$t('common.addSuccess'));
            this.assessOpen = false;
          } finally {
            this.pageLoading = false;
          }
          this.getList();
        }
      });
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      try {
        const agentIds = row.agentId || this.ids;
        await this.$modal.confirm(this.$t('common.isDelete'));
        this.pageLoading = true;
        await delAgent(agentIds);
        this.getList();
        this.$modal.msgSuccess(this.$t('common.deleteSuccess'));
      } catch (error) {
        // 处理错误
      } finally {
        this.pageLoading = false;
      }
    },

    async handleAssess(row) {
      try {
        this.assessOpen = true;
        this.assessTitle = this.$t('target.newAssessment')
        const {agentId, agentName, areaId, agentType, agentLevel, parentSalerName = '-', parentAgentName = '-'} = row;
        if (!agentId) {
          this.$modal.msgError(this.$t('common.dataError'));
        }
        this.resetForm("assessForm");

        this.assessForm = {
          agentId,
          agentName,
          areaId,
          agentType,
          agentLevel,
          parentSalerName,
          parentAgentName,
          targetYear: null,
          targetElevatorCount: null,
          targetMoney: null,
          targetProjectCount: null,
          currency: null,
        };
      } finally {

      }
    },


    /** 导出按钮操作 */
    handleExport() {
      const fileName = this.$t('agent.exportFielName') + parseTime(new Date(), '{y}{m}{d}') + '.xlsx'
      const {protocolStartDate, protocolEndDate, ...params} = this.queryParams
      this.download('user/agent/export', {
        ...params,
        agentIds: this.ids || null
      }, fileName)
    },


    // 代理商状态修改
    handleStatusChange(row) {
      const text = row.status === "0" ? this.$t('common.enabled') : this.$t('common.disabled');
      this.$modal.confirm(`${this.$t('common.confirm')}${text}[${row.agentName}]?`).then(() => {
        return changeAgentStatus(row.agentId, row.status, row.updateTime);
      }).then(() => {
        // this.$modal.msgSuccess(text + this.$t('common.enableSuccess'));
        this.$modal.msgSuccess(row.status === "0" ? this.$t('common.enableSuccess') : this.$t('common.deactivatSuccess'));
        this.getList();
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },

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

    convertTargetYear() {
      return this.assessForm.targetYear ? this.assessForm.targetYear + '-01-01' : null
    },

    async targetYearChange() {
      this.targetLoading = true;
      try {
        const p = { agentId: this.assessForm.agentId, targetYear: this.convertTargetYear() }
        const response = await getInfoByQuery(p)

        if (response.code === 200 && response.data) {
          this.assessForm.targetId = response.data.targetId
          this.assessForm.targetElevatorCount = response.data.targetElevatorCount
          this.assessForm.targetMoney = response.data.targetMoney
          this.assessForm.targetProjectCount = response.data.targetProjectCount
          this.assessForm.currency = response.data.currency
          // 提示选中的年份已经存在数据
          this.$message.warning(this.$t('target.yearExist'))
          this.assessTitle = this.$t('target.editAssessment')
        } else {
          this.assessForm.targetElevatorCount = null
          this.assessForm.targetMoney = null
          this.assessForm.targetProjectCount = null
          this.assessForm.currency = null
          this.assessTitle = this.$t('target.newAssessment')
        }
      } finally {
        this.targetLoading = false
      }

    },

    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.agentId || this.ids
        await this.getAreaTree();
        const response = await getAgent(agentId);
        this.form = response.data;
        // 根据区域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.agent');
      } finally {
        this.pageLoading = false;
      }
    },
  }
};
</script>

<!--style-->
<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;
  }
}


.w-100 {
  width: 100%;
}

/* 更多 按钮 样式 start */
@import "@/assets/styles/element-variables.scss";

.el-dropdown-menu {
  padding: 8px 0;

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

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

::v-deep .el-dropdown-menu__item i {
  margin-right: 12px !important;
}
/* 更多 按钮 样式 end */
</style>
