<template>
  <div class="app-container">
    <card-table :modalData="libraryList" labelWidth="120px" :searchParams="queryParams" @pagination="getListNew"
      @selection-change="handleBaseSelectionChange" :loading="loading" :tableSearch="true" @columnSearch="handleQuery"
      @resetList="resetQuery">
      <template #operations="{ selections }">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['business:library:add']">{{ $t('common.add') }}
            </el-button>
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button-->
          <!--              type="warning"-->
          <!--              plain-->
          <!--              icon="el-icon-upload2"-->
          <!--              size="mini"-->
          <!--              @click="handleExport"-->
          <!--              v-hasPermi="['business:library:export']"-->
          <!--            >{{ $t('common.export') }}</el-button>-->
          <!--          </el-col>-->
          <el-col :span="1.5">
            <!--            <el-button
                          type="warning"
                          plain
                          icon="el-icon-import"
                          size="mini"
                          @click="handleImport"
                          v-hasPermi="['business:library:import']"
                        >{{ $t('common.import') }}</el-button>-->
          </el-col>

        </el-row>
      </template>

      <template #default="{ list }">
        <el-table-column label="No" align="center" :min-width="50" fixed="left">
          <template slot-scope="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <Column :label="$t('elevatorModel.areaName')" :searchDict="areaOps" :showSearch="true" :labelProp="localLabel"
          :searchParams="queryParams" prop="areaId" searchType="select" selectMore valueProp="areaId">
          <template #default="{ row }">
            <span>{{ changeLanguage(row.areaId) }}</span>
          </template>
        </Column>
        <Column :label="$t('elevatorModel.elevatorTypeName')" align="center" prop="elevatorType" :min-width="200"
          :searchDict="dict.type.elevator_type" :selectMore="true" :searchParams="queryParams" :showSearch="true"
          searchType="select">
          <template #default="{ row }">
            <span>{{ formatDict(row.elevatorType, 'elevator_type') }}</span>
          </template>
        </Column>
        <Column :label="$t('elevatorModel.elevatorModel')" align="center" prop="elevatorModel" :min-width="150"
          :searchParams="queryParams" :showSearch="true" searchType="input" />
        <Column :label="$t('elevatorModel.status')" align="center" prop="status" :min-width="150"
          :searchDict="dict.type.status_switch" :searchParams="queryParams" :showSearch="true" searchType="select">
          <template #default="{ row }">
            <el-switch v-model="row.status" active-value="0" inactive-value="1"
              @change="handleStatusChange(row)"></el-switch>
          </template>
        </Column>
        <Column :label="$t('适用国家')" align="center" prop="targetCountry" :min-width="150" />
        <Column :label="$t('适用用户')" align="center" prop="targetUser" :min-width="150" />
        <Column :label="$t('elevatorModel.remark')" align="center" prop="remark" :min-width="150" />


        <Column :label="$t('common.operate')" :min-width="400" fixed="right" :showSearch="true" searchType="operate">
          <template #default="{ row }">
            <ImportModal style="margin-right:10px" :title="$t('common.import')" icon="el-icon-download"
              fileName="区域电梯参数信息导入模板" :tableType="3" :close="getList" :defaultParams="{ id: row.id }"
              buttonType="text" />

            <el-button size="mini" type="text" icon="el-icon-upload2" @click="handleExportCS(row)">{{
              $t('common.export') }}
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(row)"
              v-hasPermi="['business:elevator:edit']">{{ $t('common.edit') }}
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-s-unfold" @click="handleParam(row)"
              v-hasPermi="['business:elevator:paramInfo']">{{ $t('elevatorModel.areaParam') }}
            </el-button>

            <el-dropdown size="mini" @command="(command) => handleCommand(command, row)">
              <el-button icon="el-icon-d-arrow-right" size="mini" type="text">{{ $t('common.more') }}</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-hasPermi="['business:elevator:getParamItemInfo']" command="handleSelect" size="mini"
                  icon="el-icon-s-data">{{ $t('elevatorModel.selectItem') }}
                </el-dropdown-item>

                <el-dropdown-item v-hasPermi="['business:elevator:getStantInfo']" command="handleStandard" size="mini"
                  icon="el-icon-s-management">{{ $t('elevatorModel.paramStandard') }}
                </el-dropdown-item>

                <el-dropdown-item v-hasPermi="['business:library:edit']" command="handleJGB" size="mini"
                  icon="el-icon-document">{{ $t('elevatorModel.priceLine') }}
                </el-dropdown-item>

                <el-dropdown-item v-hasPermi="['business:library:remove']" command="handleDelete" size="mini"
                  icon="el-icon-delete">{{ $t('common.delete') }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

            <!--            <el-button size="mini" type="text"-->
            <!--                       icon="el-icon-edit" @click="handleSelect(row)"-->
            <!--                       v-hasPermi="['business:elevator:getParamItemInfo']">{{ $t('elevatorModel.selectItem') }}</el-button>-->
            <!--            <el-button size="mini" type="text"-->
            <!--                       icon="el-icon-edit" @click="handleStandard(row)"-->
            <!--                       v-hasPermi="['business:elevator:getStantInfo']">{{ $t('elevatorModel.paramStandard') }}</el-button>-->
            <!--            <el-button size="mini" type="text"-->
            <!--                       icon="el-icon-edit" @click="handleJGB(row)"-->
            <!--                       v-hasPermi="['business:library:edit']">{{ $t('elevatorModel.priceLine') }}</el-button>-->
            <!--            <el-button size="mini" type="text"-->
            <!--                       icon="el-icon-delete" @click="handleDelete(row)"-->
            <!--                       v-hasPermi="['business:library:remove']">{{ $t('common.delete') }}</el-button>-->

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

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="760px" append-to-body :close-on-click-modal="false" @close="reset">
      <el-form ref="form" :model="form" :rules="rules" class="area-form" label-position="top">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item :label="$t('elevatorModel.areaName')" prop="areaId">
              <treeselect v-model="form.areaId" :flat="true" :options="areaTree"
                :noResultsText="$t('common.noResultsText')" :placeholder="$t('user.placeholder_area')"
                :show-count="true" :append-to-body="true" :zIndex="999999"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('elevatorModel.elevatorModel')" prop="elevatorModel">
              <el-input v-model.trim="form.elevatorModel"
                :placeholder="$t('common.pleaseInput') + $t('elevatorModel.elevatorModel')" :maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <Select :label="$t('elevatorModel.elevatorTypeName')" prop="elevatorType" :data="dict.type.elevator_type"
              :placeholder="$t('common.pleaseSelect') + $t('elevatorModel.elevatorTypeName')" required />
          </el-col>
          <el-col :span="12">
            <Select :label="$t('elevatorModel.status')" prop="status" :data="dict.type.status_switch"
              :placeholder="$t('common.pleaseSelect') + $t('elevatorModel.status')" required />
          </el-col>
        </el-row>
        <el-row>
          <el-col style="margin-bottom: 20px">
            <el-button type="primary" @click="selectAllCut">全选</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item :label="$t('适用国家')" prop="countryIds">
            <el-transfer class="transfer-box" ref="myTransfer" v-model="form.countryIds" :data="nationList" filterable
              :filter-placeholder="$t('common.pleaseInput')" style="width: 100%"></el-transfer>
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item :label="$t('适用对象')" prop="trainingTargets">
            <el-button @click="addTargetsDialog" type="primary" size="mini">{{
              $t('trainList.addObject')
            }}
            </el-button>
          </el-form-item>
        </el-row>

        <card-table :loading="loading" :modalData="targetsList" style="width: 100%;margin: 0 0 20px 0"
          :searchParams="targetQueryParams">
          <el-table-column label="No" type="index" />
          <el-table-column :label="$t('user.nick')" prop="nickName" />
          <Column :label="$t('user.role')" prop="roleId">
            <template #default="{ row }">
              <span>{{ row.roleNames }}</span>
            </template>
          </Column>
          <Column :label="$t('user.agent')" prop="agentName">
            <template #default="{ row }">
              <span v-if="row.deptId == 0">{{ $t('common.head') }}</span>
              <span v-else>{{ row.agentName }}</span>
            </template>
          </Column>

          <el-table-column :label="$t('common.operate')" align="center">
            <template #default="{ row }">
              <el-button v-hasPermi="['train:list:delete']" icon="el-icon-delete" size="mini" type="text"
                @click="deleteTarget(row)">{{ $t('common.delete') }}
              </el-button>
            </template>
          </el-table-column>
        </card-table>

        <el-row>
          <el-col :span="24">
            <Input :label="$t('elevatorModel.remark')" prop="remark" type="textarea" :maxlength="250" width="100%" />
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-circle-check" type="primary" @click="submitForm">{{ $t('common.confirm') }}</el-button>
        <el-button icon="el-icon-remove-outline" @click="cancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
    <!--参数选配-->
    <el-dialog :title="title" :visible.sync="openXP" top="5%" width="70%" append-to-body :close-on-click-modal="false">
      <el-form ref="formXP" :model="formXP" label-width="120px" v-if="openXP">
        <el-row>
          <el-col :span="8">
            <Select :label="$t('elevatorModel.areaName')" prop="areaId" :labelProp="localLabel" valueProp="areaId"
              :data="areaOps" :placeholder="$t('common.pleaseSelect')" disabled />
            <!--            <el-form-item :label="$t('elevatorModel.areaName')" prop="areaId">-->
            <!--            </el-form-item>-->
          </el-col>
          <el-col :span="8">
            <Select :showTip="true" :label="$t('elevatorModel.elevatorTypeName')" prop="elevatorType"
              :data="dict.type.elevator_type" :placeholder="$t('common.pleaseSelect')" disabled />
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('elevatorModel.elevatorModel')" prop="elevatorModel">
              <el-input v-model="formXP.elevatorModel" :placeholder="$t('common.pleaseInput')" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="padding-left: 80px">
            <h3>{{ $t('elevatorModel.paramSelect') + '：' }}</h3>
            <el-select v-model="transferQuery" placeholder="请选择" @change="changeQuery" allow-create filterable
              style="margin-bottom: 5px">
              <el-option v-for="item in transferQueryOpt" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
            <el-transfer class="paraSelect" ref="paraSelect" v-model="paraSelectList" :data="paraLibraryListOpt"
              :titles="[$t('elevatorModel.allParam'), $t('elevatorModel.isSelect')]" :filterable="true">
              <span slot-scope="{ option }">
                <el-tooltip class="item" effect="dark" :content="option.label" placement="left">
                  <span>{{ option.label }}</span>
                </el-tooltip>
              </span>
            </el-transfer>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-circle-check" type="primary" @click="submitXPForm">{{ $t('common.confirm')
          }}</el-button>
        <el-button icon="el-icon-remove-outline" @click="cancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
    <!--参数选项-->
    <el-dialog :title="title" :visible.sync="openSelectOpt" top="5%" width="90%" append-to-body
      :close-on-click-modal="false">
      <el-form ref="formSelectOpt" :model="formSelectOpt" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <Select :label="$t('elevatorModel.areaName')" prop="areaId" labelWidth="50px" :labelProp="localLabel"
              valueProp="areaId" :data="areaOps" :placeholder="$t('common.pleaseSelect')" disabled />
            <!--            <el-form-item :label="$t('elevatorModel.areaName')" prop="areaId">-->
            <!--            </el-form-item>-->
          </el-col>
          <el-col :span="8">
            <Select :label="$t('elevatorModel.elevatorTypeName')" prop="elevatorType" :data="dict.type.elevator_type"
              :placeholder="$t('common.pleaseSelect')" disabled />
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('elevatorModel.elevatorModel')" prop="elevatorModel">
              <el-input v-model="formSelectOpt.elevatorModel" :placeholder="$t('common.pleaseInput')" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col style="margin-bottom: 20px">
            <el-button type="primary" @click="selectAll">一键全选</el-button>
          </el-col>
        </el-row>
        <el-row>
          <div v-if="formSelectOpt.tabsList && formSelectOpt.tabsList.length == 0">
            <el-empty description="暂无数据"></el-empty>
          </div>
          <el-tabs type="border-card" v-else style="box-shadow: unset">
            <el-tab-pane v-for="item in formSelectOpt.tabsList" :label="getParaLabel(item.paraCategory)"
              style="height: 440px;overflow: auto">
              <el-col :span="12" style="padding-left: 80px" v-for="para in item.paraSelect">
                <h3>{{ para[localParaLabel] }}</h3>
                <el-transfer v-model="para.paraAreaSelectList" :data="para.paraSelectListOpt"
                  :titles="[$t('elevatorModel.allParam'), $t('elevatorModel.isSelect')]" @change="changeEditFlag(para)">
                  <span slot-scope="{ option }">
                    <el-tooltip class="item" effect="dark" :content="option.label" placement="left">
                      <span>{{ option.label }}</span>
                    </el-tooltip>
                  </span>
                </el-transfer>
              </el-col>
            </el-tab-pane>
          </el-tabs>

        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-circle-check" type="primary" @click="submitSelectForm"
          :disabled="formSelectOpt.tabsList && formSelectOpt.tabsList.length == 0">{{ $t('common.confirm')
          }}</el-button>
        <el-button icon="el-icon-remove-outline" @click="cancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>
    <!--参数默认值选项-->
    <el-dialog :title="title" :visible.sync="openStand" top="5%" width="90%" append-to-body
      :close-on-click-modal="false">
      <el-form ref="formStand" :model="formStand" label-width="120px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="8">
            <Select :label="$t('elevatorModel.areaName')" prop="areaId" :labelProp="localLabel" label-width="50px"
              valueProp="areaId" :data="areaOps" :placeholder="$t('common.pleaseSelect')" disabled />
            <!--            <el-form-item :label="$t('elevatorModel.areaName')" prop="areaId">-->
            <!--            </el-form-item>-->
          </el-col>
          <el-col :span="8">
            <Select :label="$t('elevatorModel.elevatorTypeName')" prop="elevatorType" :data="dict.type.elevator_type"
              :placeholder="$t('common.pleaseSelect')" disabled />
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('elevatorModel.elevatorModel')" prop="elevatorModel">
              <el-input v-model="formStand.elevatorModel" :placeholder="$t('common.pleaseInput')" disabled />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form ref="formStand" :model="formStand" label-width="150px" label-position="top">
        <el-row>
          <div v-if="formStand.tabsList && formStand.tabsList.length == 0">
            <el-empty description="暂无数据"></el-empty>
          </div>
          <el-tabs type="border-card" v-else style="box-shadow: unset">
            <el-tab-pane v-for="item in formStand.tabsList" :label="getParaLabel(item.paraCategory)"
              style="height: 440px;overflow: auto">
              <el-col :span="8" style="" v-for="para in item.paraSelect">
                <!--                <h3>{{ para[localParaLabel]}}</h3>-->
                <el-form-item :label="para.inputType == '05' ? ' ' : para[localParaLabel]" label-width="150px"
                  class="stand-input">
                  <!--                根据类型，普通输入00 / 数字输入01 /下拉框02 /小数下拉框03 /04可输入下拉框 -->

                  <el-input v-if="para.inputType == '00'" :label="para[localParaLabel]" clearable
                    v-model.trim="para.paraDefaultValue" :placeholder="$t('common.pleaseInput')"
                    @change="changeEditFlag(para)" />

                  <el-input-number v-if="para.inputType == '01'" v-model="para.paraDefaultValue"
                    :placeholder="$t('common.pleaseInput')" clearable style="text-align: left" :min="0" :max="99999"
                    :precision="0" :controls="false" @change="changeEditFlag(para)" />

                  <el-select v-if="para.inputType == '02'" v-model="para.paraDefaultValue"
                    :placeholder="$t('common.pleaseSelect')" @change="value => setSelectId(value, para)" clearable>
                    <el-option v-for="item in para.selectItemList" :key="item.value" :label="item[localSelectLabel]"
                      :value="item.value">
                    </el-option>
                  </el-select>


                  <el-input-number v-if="para.inputType == '03'" v-model="para.paraDefaultValue"
                    :placeholder="$t('common.pleaseInput')" clearable style="text-align: left" :min="0" :max="99999"
                    :precision="2" :controls="false" @change="changeEditFlag(para)" />

                  <el-select v-if="para.inputType == '04'" v-model="para.paraDefaultValue"
                    :placeholder="$t('common.pleaseSelect')" allow-create filterable clearable
                    @change="value => setSelectId(value, para)">
                    <el-option v-for="item in para.selectItemList" :key="item.value" :label="item[localSelectLabel]"
                      :value="item.value">
                    </el-option>
                  </el-select>

                  <!--                    复选框-->
                  <div v-if="para.inputType == '05'" style="height: 30px"></div>
                  <el-checkbox v-if="para.inputType == '05'" v-model="para.paraDefaultValue" :true-label="'Yes'"
                    :false-label="'No'" class="para-checkbox" @change="changeEditFlag(para)">
                    <span style="font-weight: 700;line-height: 36px;font-size: 14px;color:#606266;">{{
                      para[localParaLabel]
                    }}</span>
                  </el-checkbox>
                </el-form-item>
              </el-col>
            </el-tab-pane>
          </el-tabs>
        </el-row>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-circle-check" type="primary" @click="submitStandForm"
          :disabled="formStand.tabsList && formStand.tabsList.length == 0">{{ $t('common.confirm') }}</el-button>
        <el-button icon="el-icon-remove-outline" @click="cancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>

    <!--价格表设定-->
    <el-dialog :title="title" :visible.sync="openJGB" top="5%" width="90%" append-to-body>
      <el-form ref="formSelectOpt" :model="formJGB" label-width="120px">
        <el-row>
          <el-col :span="8">
            <Select :label="$t('elevatorModel.areaName')" prop="areaId" :labelProp="localLabel" valueProp="areaId"
              :data="areaOps" :placeholder="$t('common.pleaseSelect')" disabled />
          </el-col>
          <el-col :span="8">
            <Select :label="$t('elevatorModel.elevatorTypeName')" prop="elevatorType" :data="dict.type.elevator_type"
              :placeholder="$t('common.pleaseSelect')" disabled />
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('elevatorModel.elevatorModel')" prop="elevatorModel">
              <el-input v-model="formJGB.elevatorModel" :placeholder="$t('common.pleaseInput')" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <ImportModal style="margin-left:10px" title="导入" icon="el-icon-download" fileName="区域电梯参数信息导入模板"
              tableType="3" :close="getList" :defaultParams="{ id: 1 }" />
            <el-button type="primary" @click="submitSelectForm">导出</el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-tabs type="border-card">
            <el-tab-pane :label="$t('elevatorModel.JJManage')" style="height: 540px;overflow: auto">
              <el-col :span="12" style="padding-left: 0px;margin-bottom: 10px">
                <h3>基础价格</h3>
                <el-button @click="cancel">{{ }}新增行</el-button>
                <el-button @click="cancel">{{ }}删除行</el-button>
                <el-button @click="cancel">{{ $t('common.cancel') }}复制行</el-button>
              </el-col>
              <el-table ref="table" :data="formJGB.baseData" v-loading="JJLoading" row-key="id"
                @selection-change="handleSelectionChange" class="page-table" :row-style="{ 'height': '8px' }"
                max-height="520px" :border="true"
                :header-cell-style="{ 'background-color': '#F4F6F8', 'border-right': '1px solid #dfdcdc', 'color': '#92A2B5' }">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column prop="ratedLoadCapacity" label="额定载重(kg)" width="200px">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.ratedLoadCapacity" style="width: 92%;" :disabled="disabled"
                      :min="0" :max="99999" :precision="2" class="custom-number" />
                  </template>
                </el-table-column>
                <el-table-column prop="ratedSpeed" label="额定速度(m/s)" width="200px">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.ratedSpeed" style="width: 92%;" :disabled="disabled" :min="0"
                      :max="99999" :precision="2" class="custom-number" />
                  </template>
                </el-table-column>
                <InputNumberColumn prop="standardDoorWidth" label="开门宽" />
                <InputNumberColumn prop="standardDoorHeight" label="开门高" />
                <InputNumberColumn prop="maxLiftingHeight" label="最大提示高度" />
                <InputNumberColumn prop="standardFloors" label="标准层站数" />
                <InputNumberColumn prop="basicPrice" label="基础价格" />
                <InputNumberColumn prop="addOnefloorPrice" label="层站加价" />
                <InputNumberColumn prop="subtractOnefloorPrice" label="层站减价" />
              </el-table>
            </el-tab-pane>
            <el-tab-pane :label="$t('elevatorModel.XPManage')" style="height: 540px;overflow: auto">
              <el-col :span="12" style="padding-left: 80px">
                <h3>选配项目</h3>
                <el-table ref="table" :data="formJGB.JJData" v-loading="JJLoading" row-key="id"
                  @selection-change="handleSelectionChange" class="page-table" :row-style="{ 'height': '8px' }"
                  max-height="520px" :border="true"
                  :header-cell-style="{ 'background-color': '#F4F6F8', 'border-right': '1px solid #dfdcdc', 'color': '#92A2B5' }">
                  <el-table-column type="selection" width="55" align="center" />
                  <el-table-column prop="contactName" :label="$t('contact.name')" width="200px">
                    <template slot-scope="scope">
                      <el-input v-model.trim="scope.row.contactName" :disabled="type == 'view'"
                        maxlength="30"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column prop="phone" :label="$t('contact.phone')" width="200px">
                    <template slot-scope="scope">
                      <el-input v-model.trim="scope.row.phone" :disabled="type == 'view'" maxlength="30"></el-input>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-tab-pane>
          </el-tabs>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSelectForm">{{ $t('common.confirm') }}</el-button>
        <el-button @click="cancel">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>

    <!--  添加适用对象弹出层-->
    <el-dialog :close-on-click-modal="false" :title="$t('适用对象选择')" :visible.sync="isAddTargets" append-to-body
      custom-class="edit-dialog" width="50vw">
      <card-table-zy ref="userTable" :modalData="userList" labelWidth="120px"
        :searchParams="userQueryParams" @pagination="getUserList" :loading="targetLoading" :tableSearch="true"
        :reserve-selection="true" @cancel="handleUserCancel" @select="handleUserSelect" @columnSearch="getUserList" @resetList="resetQueryUserSelect"
        :delProp="['createTime']">
        <el-table-column type="selection" width="50" align="center" />
        <!--        <Column :label="$t('user.account')" prop="userName" :searchParams="userQueryParams" :showSearch="true"/>-->
        <Column :label="$t('user.nick')" prop="nickName" :searchParams="userQueryParams" :showSearch="true" />
        <Column :label="$t('user.role')" prop="roleId" @selectChange="getUserList" :searchParams="userQueryParams"
          :showSearch="true" searchType="select" :searchDict="allRoleOptions" valueProp="roleId" labelProp="roleName">
          <template #default="{ row }">
            <span>{{ row.roleNames }}</span>
          </template>
        </Column>
        <Column :label="$t('user.area')" prop="areaId" :searchParams="userQueryParams" :showSearch="true"
          searchType="select" :searchDict="areaOps" @selectChange="getUserList" valueProp="areaId" labelProp="areaName">
          <template #default="{ row }">
            <span>{{ row.areaName }}</span>
          </template>
        </Column>
        <!--                        <Column :label="$t('user.agent')" prop="agentName"/>-->
        <Column :label="$t('user.agent')" prop="agentName">
          <template #default="{ row }">
            <span v-if="row.deptId == 0">{{ $t('common.head') }}</span>
            <span v-else>{{ row.agentName }}</span>
          </template>
        </Column>
        <Column :label="$t('common.operate')" :min-width="200" :showSearch="true" align="center" fixed="right"
                search-type="operate"
                width="250px">
        </Column>
      </card-table-zy>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-circle-check" type="primary" @click="submitTargetsForm">{{
          $t('common.confirm')
        }}
        </el-button>
        <el-button icon="el-icon-remove-outline" @click="isAddTargets = false">{{
          $t('common.cancel')
        }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import { listModel, getModel, delModel, addModel, updateModel, changeEleStatus, getArea, listModelNew, getModelParam, getModelSelecItem, getModelStandItem, getModelJgbInfo, delModelCheck } from "@/api/business/crm/elevatorModel.js";
import { updateModelParam } from "@/api/business/crm/areaPara.js";
import { updateModelSelect } from "@/api/business/crm/areaSelectItem.js";
import { updateModelStand } from "@/api/business/crm/standard.js";

import { listLibrary } from "@/api/business/crm/paralibrary/library.js";

import ImportModal from "../../../components/ImportModal/index";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getCountryByAreaId } from "@/api/system/user";
import { getAreaTree } from "@/api/common/common";
import InputColumn from "../../../components/element/table/InputColumn";
import InputNumberColumn from "../../../components/element/table/InputNumberColumn";
import { downloadTemplate } from '@/api/excel'
import { getAllNationList } from "@/api/user/country";
import { getUser, listUserWithoutAdmin } from "@/api/system/user";
import cardTableZy from "@/components/element/table/CardTableZy.vue";

export default {
  name: "ElevatorModel",
  components: { InputNumberColumn, InputColumn, Treeselect, ImportModal,cardTableZy },
  dicts: ['input_type', 'para_category', 'elevator_type', 'status_switch'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      libraryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        areaId: null,
        elevatorType: null,
        elevatorModel: null,
        status: null,
      },
      // 表单参数
      form: {
        areaId: null,
        areaName: null,
        elevatorType: null,
        elevatorModel: null,
        remark: null,
        status: null,
      },
      // 表单校验
      rules: {
        areaId: [
          { required: true, message: this.$t('common.pleaseSelect') + this.$t('elevatorModel.areaName'), trigger: 'blur' }
        ],
        elevatorType: [
          { required: true, message: this.$t('common.pleaseSelect') + this.$t('elevatorModel.elevatorTypeName'), trigger: 'blur' }
        ],
        elevatorModel: [
          { required: true, message: this.$t('common.pleaseInput') + this.$t('elevatorModel.elevatorModel'), trigger: 'blur' }
        ],
        status: [
          { required: true, message: this.$t('common.pleaseSelect') + this.$t('elevatorModel.status'), trigger: 'blur' }
        ],
        remark: [
          { required: true, message: this.$t('common.pleaseInput') + this.$t('elevatorModel.remark'), trigger: 'blur' }
        ],
      },
      selections: [],
      // 地区下拉
      areaOps: [],
      // 地区树
      areaTree: [],
      // 地区选项
      areaOptions: [],
      localLabel: "",
      localParaLabel: '',
      localSelectLabel: "",
      //参数选配
      openXP: false,
      //参数下拉选项
      openSelectOpt: false,
      openStand: false,
      openJGB: false,
      //穿梭框选择集合
      paraLibraryList: [],
      //穿梭框选中集合
      paraAreaSelectList: [],
      paraSelectListOpt: [],
      paraLibraryListOpt: [],
      formXP: {},
      formSelectOpt: {},
      formStand: {},
      formJGB: {},
      tabsList: [{}],
      paraSelectList: [],
      transferQuery: "",
      transferQueryOpt: [],
      JJData: [],
      JJLoading: false,
      selectionsJGB: [],
      localDictLabel: "",
      exportLoading: true,
      targetQueryParams: {},
      targetsList: [],
      nationList: [],
      targetLoading: false,
      // 用户查询参数
      userQueryParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
        nickName: null,
        roleId: null,
        areaId: null,
      },
      allRoleOptions: [],
      isAddTargets: false,
      // 被选择的用户列表
      userSelectionListNowSet: new Set(),
      selectUserIdSet: new Set(),
      // 所有用户列表
      userList: [],
    };
  },
  created() {
    this.setLabel();
    this.getList();
    this.getAreaOps();
    this.getAreaTree();
    this.getParamLibraryList();
  },
  methods: {
    // 新增或修改弹窗清空
    resetForm(){

    },
    // 获取地区下拉框
    getArea() {
      getArea().then(response => {
        this.areaOptions = response.data;
        console.log('allAreaList', this.areaOptions)
      });
    },
    /** 导出按钮操作 */
    handleExportCS(row) {
      this.loading = true
      const fileName = this.changeLanguage(row.areaId) + "_" + row.elevatorModel + '_梯型参数_' + this.parseTime(new Date(), '{y}{m}{d}') + '.xlsx'
      downloadTemplate({ tableType: 7, elevatorModelId: row.id, withData: true, downloadFileName: fileName }).then(response => {
        if (response) {
          this.$modal.msgError('导出失败');
        }
      }).finally(() => this.loading = false)

      // const fileName = row.elevatorModel+'_区域电梯参数导入模板下载_' + this.parseTime(new Date(), '{y}{m}{d}') + '.xlsx'
      // downloadTemplate({ tableType: 3, elevatorModelId: row.id, withData: true, downloadFileName: fileName })
      //   .finally(() => this.loading = false)
    },
    handleCommand(command, row) {
      switch (command) {
        case "handleSelect":
          this.handleSelect(row);
          break;
        case "handleStandard":
          this.handleStandard(row);
          break;
        case "handleJGB":
          this.handleJGB(row);
          break;
        case "handleDelete":
          this.handleDelete(row);
          break;
        default:
          break;
      }
    },
    //设置输入类型下拉框
    setInputType() {
      let dicts = JSON.parse(JSON.stringify(this.dict.type.para_category))
      dicts.some(item => {
        item.value = item.label
      })
      this.transferQueryOpt = dicts
    },
    changeQuery(val) {
      if (!val || val == "") {
        val = this.transferQueryOpt[0].value
      }
      this.$refs.paraSelect.$refs.leftPanel.query = val;
    },
    // 权限下拉框
    getAllRoleOptions() {
      getUser().then(response => {
        this.allRoleOptions = response.roles;
      });
    },
    /** 查询【请填写功能名称】列表 */
    getListNew(params) {
      this.loading = true;
      listModelNew(params).then(response => {
        this.libraryList = response.rows;
        this.total = response.total;
        this.queryParams.total = response.total;
        this.loading = false;
      });
    },
    getList() {
      this.loading = true;
      listModelNew(this.queryParams).then(response => {
        this.libraryList = response.rows;
        this.total = response.total;
        this.queryParams.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openXP = false;
      this.openSelectOpt = false;
      this.openStand = false;
      this.openJGB = false;
      this.reset();
      this.resetXP()
      this.resetSelectOpt()
      this.resetStand()
      this.resetJGB()
    },
    // 表单重置
    reset() {
      this.form = {
        areaId: null,
        elevatorType: null,
        elevatorModel: null,
        remark: null,
        status: null,
      }
      this.targetsList = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery(item) {
      this.queryParams.pageNum = 1;
      item.pageNum = 1;
      this.getListNew(item);
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.queryParams.areaName = null;
      this.queryParams.elevatorType = null;
      this.queryParams.remark = null;
      this.queryParams.elevatorModel = null;
      this.queryParams.status = null;
      this.queryParams.areaId = [];
      this.getList();
    },
    // 多选框选中数据
    handleBaseSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.selections = selection
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      if(this.$refs["form"]){
        this.$refs["form"].resetFields();
      }
      this.open = true;
      this.title = this.$t('paraLibrary.addParameter');
      this.targetsList = []
      this.userSelectionListNowSet = new Set()
      this.selectUserIdSet = new Set()
      this.getNationList()

    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids

      const response = await getModel(id);
      this.form = response.data;
      this.$set(this.form, 'countryIds', this.form.targetCountryIds?.split(",").filter(id => Boolean(id)).map(id => Number(id)) || [])
      this.$set(this.form, 'userIds', this.form.targetUserIds?.split(",").filter(id => Boolean(id)).map(id => Number(id)) || [])
      // 已存在培训对象数据放入回显
      this.form.userIds?.forEach(item => {
        this.selectUserIdSet.add(item)
      })
      // this.getCountryByAreaId(this.form.areaId)
      await this.getNationList()
      this.targetsList = response.data.targetUsers || []
      this.open = true;
      this.title = this.$t('paraLibrary.editParameter');
    },
    /** 提交按钮 */
    submitForm() {
      this.form.targetUserIds = this.form.userIds?.join(",")
      this.form.targetCountryIds = this.form.countryIds?.join(",")
      if (this.form.targetUserIds) {
        this.form.targetUserIds = `,${this.form.targetUserIds},`
      }
      if (this.form.targetCountryIds) {
        this.form.targetCountryIds = `,${this.form.targetCountryIds},`
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateModel(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.editSuccess'));
              this.open = false;
              this.getList();
            });
          } else {
            addModel(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('common.addSuccess'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(this.$t('common.isDelete')).then(function () {
        // return delModel(ids);
        debugger
        return delModelCheck([row]);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('common.deleteSuccess'));
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.queryParams.language = this.$i18n.locale;
      this.download('business/library/export', {
        ...this.queryParams
      }, `library_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
    },

    // 字典值format
    formatDict(value, dictType) {
      let labelStr = '';
      for (let i = 0; i < this.dict.type[dictType].length; i++) {
        let item = this.dict.type[dictType][i]
        if (item.value == value) {
          labelStr = item.label;
          break;
        }
      }
      return labelStr;
    },
    // 参数状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? this.$t('common.enableSuccess') : this.$t('common.deactivatSuccess');
      let conformMsg = row.status === "0" ? this.$t('common.enableConfirmMsg') : this.$t('common.deactivatConfirmMsg');
      this.$modal.confirm(conformMsg + this.$t('elevatorModel.elevatorModel') + '=' + row.elevatorModel).then(function () {
        return changeEleStatus(row.id, row.status, row.updateTime);
      }).then(() => {
        this.$modal.msgSuccess(text);
        this.getList();
      }).catch(function () {
        row.status = row.status === "0" ? "1" : "0";
      });
    },

    // 获取地区树
    getAreaTree() {
      getAreaTree().then(response => {
        this.areaTree = response.data;
        console.log('allAreaList', this.areaTree)
        // 将根节点设置 isDisabled: true
        // if (this.areaTree.length > 0) {
        //   this.areaTree[0].isDisabled = true;
        // }
      });
    },
    async getAreaOps() {
      const response = await getArea();
      this.areaOps = response.data;
    },
    //设置本地语音label
    setLabel() {
      let currentLocale = window.VueI18n.locale;
      switch (currentLocale) {
        case "chinese":
          this.localLabel = "areaName"
          this.localParaLabel = "paraName"
          this.localSelectLabel = "label"
          this.localDictLabel = "dict_label"
          break
        case "english":
          this.localLabel = "areaNameUS"
          this.localParaLabel = "paraNameUS"
          this.localSelectLabel = "labelUS"
          this.localDictLabel = "dict_labelUS"
          break
        case "russia":
          this.localLabel = "areaNameRU"
          this.localParaLabel = "paraNameRU"
          this.localSelectLabel = "labelRU"
          this.localDictLabel = "dict_labelRU"
          break
        case "spanish":
          this.localLabel = "areaNameES"
          this.localParaLabel = "paraNameES"
          this.localSelectLabel = "labelES"
          this.localDictLabel = "dict_labelES"
          break
      }
    },
    //改变语言
    changeLanguage(id) {
      let res = this.selectLabelList(this.areaOps, id, this.localLabel, "areaId");
      return res ? res : "-"
    },
    //跳转
    jump() {
      let query = {
        test: 's'
      };
      this.$router.push({ path: "/system/notice", query: query });
    },
    //参数选配
    async handleParam(row) {
      this.setInputType();
      //处理数据让他成为穿梭框数据
      this.paraLibraryListOpt = this.changeTransfer(this.paraLibraryList.filter(it => it.elevatorType === row.elevatorType), this.localParaLabel, "id")

      this.resetXP();
      const id = row.id || this.ids
      const response = await getModelParam(id);
      if (response.data) {
        //处理数据，赋值为穿梭框选中集合
        this.formXP = response.data;
        if (this.formXP.paraSelect) {
          //已经保存过了
          this.paraSelectList = this.formXP.paraSelect.map(it => it.paramId)
        }
      }
      this.openXP = true;
      this.title = this.$t('elevatorModel.XPParameter');

      setTimeout(() => {
        this.transferQuery = this.transferQueryOpt[0].value;
        this.$refs.paraSelect.$refs.leftPanel.query = this.transferQuery;
      }, 200)

    },
    //参数选项
    async handleSelect(row) {
      this.resetSelectOpt();
      const id = row.id || this.ids
      const response = await getModelSelecItem(id);
      //处理数据，赋值为穿梭框选中集合
      this.formSelectOpt = response.data;
      if (!this.formSelectOpt.tabsList) {
        //设定不能保存
      }
      this.openSelectOpt = true;
      this.title = this.$t('elevatorModel.optSet');
    },
    //选配参数一键全选
    selectAll() {
      this.formSelectOpt.tabsList.some(it => {
        it.paraSelect.some(sel => {
          sel.paraAreaSelectList = sel.paraSelectListOpt.map(item => item.key)
          sel.operationFlag = 2
        })
      })
    },
    //国家全选
    selectAllCut() {
      debugger
      let ids = this.nationList.map(item => item.key)
      this.$set(this.form,'countryIds',ids)

    },
    resetXP() {
      this.formXP = {
        areaId: null,
        elevatorType: null,
        elevatorModel: null,
        remark: null,
        status: null,
        paraSelect: [],
      }
      this.paraSelectList = []
    },
    resetSelectOpt() {
      this.formSelectOpt = {
        areaId: null,
        elevatorType: null,
        elevatorModel: null,
        remark: null,
        status: null,
        TabsList: [],
      }
    },
    resetStand() {
      this.formStand = {
        areaId: null,
        elevatorType: null,
        elevatorModel: null,
        remark: null,
        status: null,
        tabsList: [],
      }
    },
    //获取全部的参数列表
    getParamLibraryList() {
      let params;
      params = {
        pageNum: 0,
        pageSize: 0,
        status: 0,
      };
      listLibrary(params).then(response => {
        this.paraLibraryList = response.rows;
        //处理数据让他成为穿梭框数据
        // let opts = []
        // this.paraLibraryList.some(item=>{
        //   let opt = {
        //     key:item.id,
        //     label:item[this.localParaLabel],
        //     disabled:false
        //   }
        //   opts.push(opt)
        // });
        // this.paraLibraryListOpt = this.changeTransfer(this.paraLibraryList,this.localParaLabel,"id")
      });
    },
    /** 提交XP按钮 */
    submitXPForm() {
      //只有更新
      //新增之前处理数据
      this.formXP.paraSelect = [];
      this.paraSelectList.some(item => {
        let paraLibrary = this.paraLibraryList.filter(library => library.id == item)
        let paraSelect = {
          paraId: item,
          paramId: item,
          paraCode: paraLibrary[0].paraCode,
          elevatorModelId: this.formXP.id,
          paraName: paraLibrary[0].paraName,
          sort: paraLibrary[0].sortNumber
        };
        this.formXP.paraSelect.push(paraSelect)
      });
      this.$refs["formXP"].validate(valid => {
        if (valid) {
          updateModelParam(this.formXP).then(response => {
            this.$modal.msgSuccess(this.$t('common.editSuccess'));
            this.openXP = false;
            this.getList();
          });
        }
      });
    },
    /**获取国际化*/
    getParaLabel(value) {
      let res = "-";
      let dicts = this.dict.type.para_category;
      dicts.some(it => {
        if (it.value == value) {
          res = it.label
        }
      })
      return res
    },
    /**改变编辑状态*/
    changeEditFlag(row) {
      //把状态变为已改变
      row.operationFlag = 2
    },
    /** 提交设置参数选项按钮 */
    submitSelectForm() {
      this.$refs["formSelectOpt"].validate(valid => {
        if (valid) {
          updateModelSelect(this.formSelectOpt).then(response => {
            this.$modal.msgSuccess(this.$t('common.editSuccess'));
            this.openSelectOpt = false;
            this.getList();
          });
        }
      });
    },
    /**打开默认值编辑页面*/
    async handleStandard(row) {
      this.resetStand();
      const id = row.id || this.ids
      const response = await getModelStandItem(id);
      //处理数据，赋值为穿梭框选中集合
      this.formStand = response.data;
      this.openStand = true;
      this.title = this.$t('elevatorModel.standand');
    },
    /** 提交默认值设定 */
    submitStandForm() {
      this.$refs["formStand"].validate(valid => {
        if (valid) {
          updateModelStand(this.formStand).then(response => {
            this.$modal.msgSuccess(this.$t('common.editSuccess'));
            this.openStand = false;
            this.getList();
          });
        }
      });
    },
    /**改变编辑标志并且设置修改的id*/
    setSelectId(value, row) {
      //改变编辑标志
      row.operationFlag = 2
      //设置Id值
      let arrs = row.selectItemList
      arrs.some(item => {
        if (value == item.value) {
          row.paraDefaultId = item.paraSelectItemId
        }
      });
    },

    /** 行link操作 */
    handleJGB(row) {
      this.$router.push({ path: "/para/priceForm", query: { id: row.id } });
    },
    /**打开价格表编辑页面*/
    async handleJGB1(row) {
      this.resetJGB();
      const id = row.id || this.ids
      const response = await getModelJgbInfo(id);
      //处理数据，赋值为穿梭框选中集合
      this.formJGB = response.data;
      this.openJGB = true;
      //this.title = this.$t('paraLibrary.editParameter');
      this.title = "编辑价格表"
    },
    /**选中改变*/
    handleSelectionChange(selection) {
      this.selectionsJGB = selection
    },
    resetJGB() {
      this.formJGB = {
        areaId: null,
        elevatorType: null,
        elevatorModel: null,
        remark: null,
        status: null,
        baseData: [],
        xpData: []
      }
    },
    // // 上级区域变化
    // parentAreaChange({ id: areaId }) {
    //   this.$set(this.form, 'countryIds', [])
    //   if (areaId) {
    //     // 查询上级区域拥有的国家
    //     this.getCountryByAreaId(areaId);
    //   } else if (areaId === 0) {
    //     this.getNationList()
    //   } else {
    //     this.nationList = []
    //   }
    // },
    getNationList() {
      getAllNationList().then(response => {
        this.nationList = this.formatCountry(response.data)
      })
    },
    getCountryByAreaId(areaId) {
      getCountryByAreaId(areaId).then(response => {
        this.nationList = this.formatCountry(response.data)
      })
    },
    formatCountry(list) {
      return list.map(item => {
        let label = '';
        switch (this.$i18n.locale) {
          case 'chinese':
            label = item.countryName
            break;
          case 'english':
            label = item.countryNameUS
            break;
          case 'russia':
            label = item.countryNameRU
            break;
          case 'spanish':
            label = item.countryNameES
            break;
        }
        return {
          key: item.countryId,
          label: label
        }
      })
    },
    addTargetsDialog() {
      this.isAddTargets = true;
      this.$nextTick(() => {
        this.resetQueryUserSelect()
      })
    },
    submitTargetsForm() {
      const myArray = Array.from(this.userSelectionListNowSet);
      if (myArray.length <= 0) {
        return this.isAddTargets = false;
      }
      if (this.targetsList.length > 0) {
        // 判断选择的用户列表是否都已存在于已选择的列表中
        const allSelectedAlready = myArray.every(item => this.targetsList.some(target => {
          if (target.targetPersonId) {
            return item.userId === target.targetPersonId
          } else {
            return target.userId === item.userId
          }
        }));
        if (allSelectedAlready) {
          this.$message.error(this.$t('trainList.choiceAgain'));
        } else {
          this.userSelectionListNowSet.forEach(item => {
            if (!this.targetsList.find(target => {
              if (target.targetPersonId) {
                return target.targetPersonId === item.userId
              } else {
                return target.userId === item.userId
              }
            })) {
              this.targetsList.unshift(item);
            }
          });
        }
      } else {
        this.targetsList = JSON.parse(JSON.stringify(myArray));
      }
      this.isAddTargets = false;
    },
    // 删除培训对象
    deleteTarget(row) {
      this.targetsList.splice(this.targetsList.indexOf(row), 1);
      // 删除列表数据时，也删除选中数据
      this.userSelectionListNowSet.forEach(item => {
        if (row.targetPersonId && item.userId === row.targetPersonId) {
          this.userSelectionListNowSet.delete(item);
        } else if (!row.targetPersonId && item.userId === row.userId) {
          this.userSelectionListNowSet.delete(item);
        }
      });

      const ids = this.targetsList.map(item => {
        if (item.targetPersonId) {
          return item.targetPersonId
        } else {
          return item.userId
        }
      })
      // 删除列表数据后 选中数据就是列表数据
      this.selectUserIdSet = new Set(ids)
      this.form.userIds = Array.from(this.selectUserIdSet)


    },
    resetQueryUserSelect() {
      this.userQueryParams.pageNum = 1;
      this.userQueryParams.pageSize = 10;
      this.userQueryParams.nickName = null
      this.userQueryParams.roleId = null
      this.userQueryParams.areaId = null
      this.getUserList();
    },
    // 获取人员列表
     getUserList() {
      this.targetLoading = true;
      const { createTime, ...params } = this.userQueryParams;
       listUserWithoutAdmin(params).then(async (response) => {
         this.userList = response.rows;
         this.userQueryParams.total = response.total
         // this.userSelectionList = this.userSelectionListNowSet
         // 跨页回显
         this.selectUserIdSet.clear()
         this.userSelectionListNowSet.clear()
         await this.targetsList.forEach(row => {
           this.selectUserIdSet.add(row.userId)
         })
         this.userList.forEach((row) => {
           const bool = this.selectUserIdSet.has(row.userId)
           if (bool) {
             this.$nextTick(() => {
               this.$refs['userTable'].$refs['table'].toggleRowSelection(row, true)
               const userSelectionArray = Array.from(this.userSelectionListNowSet);
               const hasItem = userSelectionArray.some(item => item.userId === row.userId);
               if (!hasItem) {
                 this.userSelectionListNowSet.add(row)
               }
             })
           }
         })
         this.getAllRoleOptions()
         this.$forceUpdate()
       }).finally(() => {
        this.targetLoading = false;
      })
    },
    handleUserSelect(rows) {
      rows.forEach(row => {
        if (!this.selectUserIdSet.has(row.userId)) {
          this.selectUserIdSet.add(row.userId)
          this.userSelectionListNowSet.add(row)
        }
      })
      this.form.userIds = Array.from(this.selectUserIdSet)
    },
    handleUserCancel(rows) {
      rows.forEach(row => {
        this.userSelectionListNowSet.forEach(item => {
          if (item.userId === row.userId) {
            this.userSelectionListNowSet.delete(item);
          }
        });
      })
    },
  }
};
</script>

<style lang="scss" scoped>
.paraSelect {
  ::v-deep .el-transfer-panel {
    width: 250px;
    height: 450px;
  }

  ::v-deep .el-transfer-panel__body {
    height: 390px;

    .el-transfer-panel__list {
      height: 390px;
    }
  }

}

.stand-input {
  ::v-deep .el-input {
    width: 300px;
  }

  ::v-deep .el-input-number {
    input {
      text-align: left;
    }

  }
}
</style>

<style lang="scss" rel="stylesheet/scss" scoped>
::v-deep .el-transfer-panel__header {
  display: none;
}

.area-form {
  padding: 0 20px;
}

::v-deep .area-form .el-form-item--medium .el-form-item__label {
  line-height: 14px;
}

::v-deep .transfer-box .el-input {
  width: auto;
}

::v-deep .transfer-box .el-transfer-panel {
  width: 240px;
}
</style>
