<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item :label="$t('服务网点')" prop="node">
        <el-select
          v-model="queryParams.nodeId"
          :placeholder="$t('所属网点')"
          :disabled="nodeId ? true : false"
          clearable
        >
          <el-option
            v-for="node in nodeList"
            :key="node.id"
            :label="node.titleZh"
            :value="node.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('关键字')" prop="keywords">
        <el-input
          v-model="queryParams.keywords"
          :placeholder="$t('请输入仓库编号/名称')"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">{{
          $t("搜索")
        }}</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">{{
          $t("重置")
        }}</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ecw:warehouse:create']"
          >{{ $t("新增") }}</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['ecw:warehouse:export']"
          >{{ $t("导出") }}</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="templateClick('')"
          v-hasPermi="['ecw:warehouse:create']"
          >{{ $t("批量设置提单模板") }}</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column :label="$t('仓库编号')" align="center" prop="number" />
      <el-table-column :label="$t('仓库名称')" align="center" prop="titleZh" />
      <el-table-column :label="$t('英文名称')" align="center" prop="titleEn" />
      <el-table-column :label="$t('贸易属性')" align="center" prop="tradeType">
        <template slot-scope="scope">
          <div>{{ tradeTypeName(scope.row.tradeType) }}</div>
        </template>
      </el-table-column>

      <el-table-column :label="$t('运输方式')" align="center" prop="freight">
        <template slot-scope="scope">
          <div>{{ transportNames(scope.row.freight) }}</div>
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('仓库容量') + '(m)³'"
        align="center"
        prop="volume"
      />
      <el-table-column
        :label="$t('仓库地址')"
        align="center"
        :prop="$l('address')"
      />
      <!--lanbm 2024-06-04 add-->
      <el-table-column
        :label="$t('仓库免租期')"
        align="center"
        prop="rentFreeDays"
      />
      <el-table-column
        :label="$t('锁定收货人天数')"
        align="center"
        prop="lockRecipientDays"
      />
      <!--end lanbm 2024-06-04 add-->
      <el-table-column prop="head" :label="$t('负责人')" align="center">
        <template slot-scope="scope">
          <div>
            <span>{{ scope.row.head }}</span>
            <br />
            <span>{{ scope.row.tell }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="status" :label="$t('状态')" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="CommonStatusEnum.ENABLE"
            :inactive-value="CommonStatusEnum.DISABLE"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>

      <el-table-column
        :label="$t('操作')"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="toRouteList(scope.row, '2')"
            :disabled="scope.row.tradeType == '2'"
            v-hasPermi="['ecw:warehouse:routerQuery']"
            >{{ $t("相关始发港") }}</el-button
          >

          <el-button
            size="mini"
            type="text"
            @click="toRouteList(scope.row, '1')"
            :disabled="scope.row.tradeType == '1'"
            v-hasPermi="['ecw:warehouse:routerQuery']"
            >{{ $t("相关目的港") }}</el-button
          >

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ecw:warehouse:update']"
            >{{ $t("修改") }}</el-button
          >

          <el-button
            size="mini"
            type="text"
            @click="bindDept(scope.row)"
            v-hasPermi="['system:dept:query']"
            >{{ $t("绑定部门") }}</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :visible.sync="showRouteList" width="900px" append-to-body>
      <el-table v-loading="routeLoadig" :data="routeList">
        <el-table-column :label="$t('序号')" type="index" width="50" />
        <el-table-column
          prop="tansportType"
          :label="$t('运输方式')"
          align="center"
        >
          <template slot-scope="scope">
            <div>
              {{ transportName(scope.row.transportType) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column :label="$t('仓库编号')" align="center" prop="number" />
        <el-table-column
          :label="$t('仓库名称')"
          align="center"
          :prop="$l('title')"
        />
        <el-table-column
          :label="$t('仓库容量') + '(m)³'"
          align="center"
          prop="volume"
        />
        <el-table-column
          :label="$t('仓库地址')"
          align="center"
          :prop="$l('address')"
        />

        <el-table-column prop="head" :label="$t('负责人')" align="center">
          <template slot-scope="scope">
            <div>
              <span>{{ scope.row.head }}</span>
              <br />
              <span>{{ scope.row.tell }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('路线服务')"
          align="center"
          prop="otherService"
        >
          <template slot-scope="scope">
            <div>{{ serviceNames(scope.row.otherService) }}</div>
          </template>
        </el-table-column>

        <el-table-column
          :label="$t('操作')"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="routeStatusClick(scope.row)"
              v-hasPermi="['ecw:warehouse:routerQuery']"
              >{{ scope.row.lineId ? "关闭线路" : "开通线路" }}</el-button
            >
            <el-button
              size="mini"
              type="primary"
              @click="templateClick(scope.row)"
              v-if="scope.row.lineId != null"
              v-hasPermi="['ecw:warehouse:routerQuery']"
              >{{ $t("设置路线提单模板") }}</el-button
            >

            <el-button
              size="mini"
              type="primary"
              @click="serviceClick(scope.row)"
              v-if="scope.row.lineId != null"
              v-hasPermi="['ecw:warehouse:routerQuery']"
              >{{ $t("开通服务") }}</el-button
            >
            <!--            <el-button size="mini" type="danger" @click="$router.push('/offer/channel-route?lineId='+scope.row.lineId)" v-if="scope.row.lineId != null && scope.row.transportType == 3" >{{$t('渠道包装清关费')}}</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination
        v-show="routeCount > 0"
        :total="routeCount"
        :page.sync="routeQueryParam.pageNo"
        :limit.sync="routeQueryParam.pageSize"
        @pagination="getRouteList"
      />
    </el-dialog>

    <el-dialog
      :title="$t('绑定部门')"
      :visible.sync="deptOpen"
      width="500px"
      append-to-body
    >
      <el-header>
        <el-button type="primary" @click="commitBind">{{
          $t("提交")
        }}</el-button>
      </el-header>

      <el-table
        ref="multipleTable"
        v-if="refreshTable"
        :data="deptList"
        row-key="id"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        @select="select"
        @select-all="selectAll"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="name" :label="$t('部门名称')"></el-table-column>
        <!-- <el-table-column prop="leader" :label="$t('负责人')" :formatter="userNicknameFormat" width="120"/> -->
      </el-table>
    </el-dialog>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item :label="$t('所属网点')" prop="nodeId">
          <el-select
            v-model="form.nodeId"
            :placeholder="$t('请选择所属网点')"
            :disabled="nodeId || isUpdate ? true : false"
            clearable
          >
            <el-option
              v-for="node in nodeList"
              :key="node.id"
              :label="$l(node, 'title')"
              :value="node.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('所在地区')" prop="area">
          <el-select
            v-model="form.zhou"
            :placeholder="$t('请选择大洲')"
            @change="changeContinents"
          >
            <el-option
              v-for="item in continentsList"
              :key="item.id"
              :label="$l(item, 'title')"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <el-select
            v-model="form.guojia"
            :placeholder="$t('请选择国家')"
            @change="changeCountry"
            v-if="form.zhou"
          >
            <el-option
              v-for="item in countryList"
              :key="item.id"
              :label="$l(item, 'title')"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <el-select
            v-model="form.sheng"
            :placeholder="$t('请选择省')"
            @change="changeProvince"
            v-if="form.guojia"
          >
            <el-option
              v-for="item in provinceList"
              :key="item.id"
              :label="$l(item, 'title')"
              :value="item.id"
            >
            </el-option>
          </el-select>
          <el-select
            v-model="form.shi"
            :placeholder="$t('请选择城市')"
            @change="changeCity"
            v-if="form.sheng"
          >
            <el-option
              v-for="item in cityList"
              :key="item.id"
              :label="$l(item, 'title')"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('排序')" prop="sort">
          <el-input
            v-model="form.sort"
            type="number"
            :placeholder="$t('请输入排序')"
          />
        </el-form-item>

        <el-form-item :label="$t('仓库编号')" prop="number">
          <el-input v-model="form.number" :placeholder="$t('请输入仓库编号')" />
        </el-form-item>
        <el-form-item :label="$t('仓库简码')" prop="qianzhui">
          <el-input
            v-model="form.qianzhui"
            :placeholder="$t('请输入仓库简码')"
          />
        </el-form-item>
        <el-form-item :label="$t('仓库名称')" prop="titleZh">
          <el-input
            v-model="form.titleZh"
            :placeholder="$t('请输入仓库名称')"
          />
        </el-form-item>
        <el-form-item :label="$t('英文名称')" prop="titleEn">
          <el-input
            v-model="form.titleEn"
            :placeholder="$t('请输入英文名称')"
          />
        </el-form-item>
        <el-form-item :label="$t('负责人')" prop="head">
          <el-input v-model="form.head" :placeholder="$t('请输入负责人')" />
        </el-form-item>
        <el-form-item :label="$t('联系电话')" prop="tell">
          <el-input v-model="form.tell" :placeholder="$t('请输入联系电话')" />
        </el-form-item>
        <el-form-item :label="$t('容量')" prop="volume">
          <el-input v-model="form.volume" :placeholder="$t('请输入容量')">
            <template slot="append">m³</template>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('仓库地址')" prop="addressZh">
          <el-input
            v-model="form.addressZh"
            :placeholder="$t('请输入仓库地址')"
          />
        </el-form-item>
        <el-form-item :label="$t('英文地址')" prop="addressEn">
          <el-input
            v-model="form.addressEn"
            :placeholder="$t('请输入英文地址')"
          />
        </el-form-item>

        <el-form-item :label="$t('贸易属性')" prop="tradeType">
          <el-select v-model="form.tradeType" :placeholder="$t('请选择')">
            <!--                     :disabled="(nodeId || isUpdate) ? true : false"-->
            <el-option
              v-for="dict in regionTypeDatas"
              :key="dict.value"
              :label="$l(dict, 'label')"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('运输方式')" prop="checkList">
          <el-checkbox-group v-model="form.checkList">
            <el-checkbox
              v-for="dict in transportDatas"
              :label="dict.value"
              :key="dict.value"
              name="freight"
            >
              {{ $l(dict, "label") }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="img" prop="img">
          <el-col :span="8">
            <el-input
              v-model="form.img"
              :placeholder="$t('请上传图片')"
              disabled
            />
          </el-col>

          <el-upload
            action="#"
            :http-request="requestUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
          >
            <el-button size="small">
              {{ $t("上传图片") }}
              <i class="el-icon-upload el-icon--right"></i>
            </el-button>
          </el-upload>
        </el-form-item>

        <el-form-item :label="$t('备注')" prop="remark">
          <el-input v-model="form.remark" :placeholder="$t('请输入备注')" />
        </el-form-item>

        <el-form-item :label="$t('会员控货下单要求')" prop="kycStatus">
          <el-radio-group v-model="form.kycStatus">
            <el-radio
              v-for="dict in kycDatas"
              :key="dict.value"
              :label="dict.value"
              >{{ $l(dict, "label") }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <!--lanbm 2024-06-04 添加控货需要的逻辑字段-->
        <el-form-item :label="$t('仓库免租期')" prop="rentFreeDays">
          <el-input-number
            v-model="form.rentFreeDays"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <el-form-item :label="$t('锁定收货人天数')" prop="lockRecipientDays">
          <el-input-number
            v-model="form.lockRecipientDays"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
      </el-form>

      <!--end lanbm 2024-06-04 添加控货需要的逻辑字段-->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{
          $t("确定")
        }}</el-button>
        <el-button @click="cancel">{{ $t("取消") }}</el-button>
      </div>
    </el-dialog>

    <!--设置服务-->
    <el-dialog
      :title="$t('设置服务')"
      :visible.sync="serviceOpen"
      width="1000px"
      append-to-body
    >
      <div style="font-size: large">
        {{ $t("线路") }}:{{
          $t("{startName}到{destName}", {
            startName: this.startName,
            destName: this.destName,
          })
        }}
        <span style="margin-left: 20px"
          >{{ $t("运输方式") }}:{{
            transportName(this.lineform.transportType)
          }}</span
        >
      </div>
      <br />

      <el-form ref="form" :model="lineform" :rules="rules" label-width="160px">
        <el-form-item :label="$t('始发港服务')">
          <el-checkbox-group v-model="lineform.otherService">
            <el-checkbox
              v-for="item in serviceGroup"
              :label="item.id"
              :key="item.id"
              :value="item.id"
            >
              {{ item.text }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item :label="$t('目的港服务')">
          <el-checkbox-group v-model="lineform.otherService">
            <template v-for="item in endServiceGroup">
              <el-checkbox
                @change="
                  () => {
                    changeOtherService(item.id);
                  }
                "
                :label="item.id"
                :key="item.id"
                :value="item.id"
                v-if="isShowError(item)"
              >
                {{ item.text }}</el-checkbox
              >
            </template>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item
          v-if="['3', '4'].includes(lineform.transportType)"
          label="空运提单制作节点"
        >
          <el-select v-model="lineform.makeBillNode">
            <el-option
              v-show="item.value !== '1'"
              v-for="(item, index) in getDictDatas(
                DICT_TYPE.AIR_SHIPMENT_PROCESS
              )"
              :label="$l(item, 'label')"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="线路是否在客户端显示">
          <el-radio-group v-model="lineform.isClientShow">
            <el-radio :label="1">可见</el-radio>
            <el-radio :label="0">不可见</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('保费币种')">
          <el-select @change="modifyAmountUnit" v-model="lineform.currencyUnit">
            <el-option
              v-for="item in currencyList"
              :disabled="item.status === 1"
              :label="$l(item, 'title')"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('最小保价费金额')">
          <el-input-number :controls="false" v-model="lineform.minPrice">
          </el-input-number>
        </el-form-item>
        <el-form-item :label="$t('是否支持控货')">
          <el-radio-group v-model="lineform.controlStatus">
            <el-radio :label="0">支持</el-radio>
            <el-radio :label="1">不支持</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--lanbm 2024-05-25 把海运的相关配置信息也显示出来了,把空运文字提示出掉了-->
        <template v-if="['3', '4', '1'].includes(lineform.transportType)">
          <el-form-item :label="$t('模板中文标题')">
            <el-input
              v-model="lineform.tempTitleZh"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('模板英文标题')">
            <el-input
              v-model="lineform.tempTitleEn"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('发件人')">
            <el-input
              v-model="lineform.senderInfo.name"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('发件人英文')">
            <el-input
              v-model="lineform.senderInfo.nameEn"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('发件公司地址')">
            <el-input
              v-model="lineform.senderInfo.companyAddress"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('发件公司地址英文')">
            <el-input
              v-model="lineform.senderInfo.companyAddressEn"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('收货人')">
            <el-input
              v-model="lineform.recipientInfo.name"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('收货人英文')">
            <el-input
              v-model="lineform.recipientInfo.nameEn"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('收货地址')">
            <el-input
              v-model="lineform.recipientInfo.companyAddress"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('收货地址英文')">
            <el-input
              v-model="lineform.recipientInfo.companyAddressEn"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <!--lanbm 2024-06-10 添加的落款信息配置信息 -->
          <el-form-item :label="$t('落款左边信息')">
            <textarea v-model="lineform.lkLeft" style="width: 400px" rows="8">
            </textarea>
          </el-form-item>
          <el-form-item :label="$t('落款右边信息')">
            <textarea v-model="lineform.lkRight" style="width: 400px" rows="8">
            </textarea>
          </el-form-item>
          <el-form-item :label="$t('落款盖章名称')">
            <el-input v-model="lineform.tzName" style="width: 400px"></el-input>
          </el-form-item>
          <!-- end lanbm 2024-06-10 添加的落款信息配置信息 -->
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitLineForm">{{
          $t("保存")
        }}</el-button>
      </div>
    </el-dialog>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog
      :title="$t('设置路线提单模板')"
      :visible.sync="templateOpen"
      width="1100px"
      @close="ladingFormClose()"
      append-to-body
    >
      <el-form ref="form" :model="ladingform" :rules="rules" label-width="80px">
        <el-form-item :label="$t('货柜前缀')" prop="prefixCounter">
          <el-input
            v-model="ladingform.prefixCounter"
            :placeholder="$t('请输入货柜前缀')"
          />
        </el-form-item>
        <el-form-item :label="$t('抬头')" prop="titleZh">
          <el-link type="primary" @click.native="setTpl('sea')">{{
            $t("海运模板")
          }}</el-link>
          |
          <el-link type="primary" @click.native="setTpl('air')">{{
            $t("空运模板")
          }}</el-link>
          <ueditor
            v-if="templateOpen"
            v-model="ladingform.titleZh"
            :min-height="192"
            style="width: 960px"
          />
        </el-form-item>

        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>{{ $t("账户详情") }}</span>
            <el-button
              style="float: right"
              size="small"
              type="primary"
              @click="handleAddAccount"
              >{{ $t("添加账户") }}+</el-button
            >
          </div>
          <el-table :data="arr" style="width: 100%">
            <el-table-column prop="detail" label="" width="">
              <template v-slot="{ row, column, $index }">
                <el-input
                  v-model="row.detail"
                  placeholder="Account detail"
                  size="mini"
                />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="" width="">
              <template v-slot="{ row }">
                <el-input
                  v-model="row.name"
                  placeholder="Account.NAME"
                  size="mini"
                />
              </template>
            </el-table-column>
            <el-table-column prop="company" label="">
              <template v-slot="{ row }">
                <el-input
                  v-model="row.company"
                  placeholder="DE-BESTDEZHI ENTERPRISE"
                  size="mini"
                />
              </template>
            </el-table-column>
            <el-table-column prop="operate" label="">
              <template slot-scope="scope">
                <el-button type="danger" @click="delRow(scope.$index)">{{
                  $t("删除")
                }}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <el-form-item :label="$t('条款')" prop="contentZh">
          <el-link
            type="primary"
            @click.native="setAgreementTpl('agreementSea')"
            >{{ $t("海运模板") }}</el-link
          >
          |
          <el-link
            type="primary"
            @click.native="setAgreementTpl('agreementAir')"
            >{{ $t("空运模板") }}</el-link
          >
          <ueditor
            v-if="templateOpen"
            v-model="ladingform.contentZh"
            :min-height="192"
            style="width: 960px"
          />
        </el-form-item>

        <el-form-item v-if="showFlag">
          <routers-selector-without-channel v-model="ladingform.lineIds" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTemplateForm">{{
          $t("保存")
        }}</el-button>
        <el-button @click="resetTemplate()">{{ $t("重置") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createWarehouse,
  updateWarehouse,
  deleteWarehouse,
  getWarehouse,
  getWarehousePage,
  createTemplate,
  getLadingTemplate,
  exportWarehouseExcel,
  routerList,
  changeRouteStatus,
  deptBind,
  deptList,
  serviceConfig,
} from "@/api/ecw/warehouse";
import { getNodePage } from "@/api/ecw/node";
import { getListTree } from "@/api/ecw/region";
import {
  getDictDatas,
  DICT_TYPE,
  getDictDataL,
  getDictDataLabel,
} from "@/utils/dict";
import { CommonStatusEnum } from "@/utils/constants";
import { uploadFile } from "@/api/infra/file";
import { listDept } from "@/api/system/dept";
import Ueditor from "@/components/Ueditor";
import { getDictData } from "@/utils/dict";
import RoutersSelectorWithoutChannel from "@/components/RoutersSelectorWithoutChannel";
import { has } from "min-dash";
import Template from "../../cms/template/index";

// 海运和空运的抬头模板
import tpl from "./tpl";
import { getCurrencyPage } from "@/api/ecw/currency";
export default {
  name: "Warehouse",
  components: {
    Template,
    Ueditor,
    RoutersSelectorWithoutChannel,
  },
  data() {
    var areaCheck = (rule, value, callback) => {
      if (!this.form.zhou) {
        callback(new Error(this.$t("请选择大洲")));
      } else if (!this.form.guojia) {
        callback(new Error(this.$t("请选择国家/地区")));
      } else if (!this.form.sheng) {
        callback(new Error(this.$t("请选择省市")));
      } else {
        callback();
      }
    };

    return {
      currencyList: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,

      //显示绑定部门
      deptOpen: false,
      //部门列表
      deptList: [],
      // 是否展开,默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      //选中的部门
      selectDeptList: [],
      //需要绑定部门的仓库id
      deptWarhouse: null,
      //洲际列表
      continentsList: [],
      //国家列表
      countryList: [],
      //省信息列表
      provinceList: [],
      //市信息列表
      cityList: [],

      serviceGroup: [
        { id: "1", text: this.$t("集运服务") },
        { id: "6", text: this.$t("数量(个)是否必填") },
      ],

      endServiceGroup: [
        { id: "3", text: this.$t("非控货订单代收货款") },
        { id: "4", text: this.$t("海外仓") },
        { id: "2", text: this.$t("送货上门") },
        { id: "5", text: this.$t("提货异常") },
        { id: "10", text: this.$t("默认送货上门") },
      ],

      // 总条数
      total: 0,
      // 仓库列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      templateOpen: false,
      dateRangeCreateTime: [],
      serviceOpen: false,
      isUpdate: false,
      nodeList: [],
      routeLoadig: false,
      showRouteList: false,
      routeList: [],
      routeCount: 0,
      routeQueryParam: {
        pageNo: 1,
        pageSize: 10,
        id: null,
        tradeType: null,
      },
      showFlag: false,
      arr: [],
      cols: [
        { prop: "detail", label: this.$t("详情") },
        { prop: "name", label: this.$t("名称") },
        { prop: "company", label: this.$t("公司") },
        { prop: "operate", label: this.$t("操作") },
      ],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        number: null,
        titleZh: null,
        titleEn: null,
        volume: null,
        addressZh: null,
        addressEn: null,
        zhou: null,
        guojia: null,
        sheng: null,
        shi: null,
        head: null,
        tell: null,
        tradeType: null,
        freight: null,
        remark: null,
        sort: null,
        status: null,
      },
      // 表单参数
      form: { checkList: [] },
      ladingform: {
        prefixCounter: null,
        titleZh: null,
        contentZh: null,
        account: null,
        acctArr: [],
      },
      lineform: {
        otherService: [],
        isClientShow: 1,
        makeBillNode: "6",
        controlStatus: "0",
        currencyUnit: 1,
        minPrice: 0,
        tempTitleZh: "",
        tempTitleEn: "",
        lkLeft: "",
        lkRight: "", //lanbm 2024-06-10 添加的落款配置信息
        tzName: "", //落款盖章 lanbm 2024-06-12 add
        recipientInfo: {
          companyAddress: "",
          companyAddressEn: "",
          name: "",
          nameEn: "",
        },
        senderInfo: {
          companyAddress: "",
          companyAddressEn: "",
          name: "",
          nameEn: "",
        },
      },
      startName: "",
      destName: "",

      // 表单校验
      rules: {
        nodeId: [
          {
            required: true,
            message: this.$t("服务网点不能为空"),
            trigger: "blur",
          },
        ],
        area: [{ validator: areaCheck, required: true, trigger: "blur" }],
        sort: [
          { required: true, message: this.$t("排序不能为空"), trigger: "blur" },
        ],
        number: [
          {
            required: true,
            message: this.$t("仓库编号不能为空"),
            trigger: "blur",
          },
        ],
        titleZh: [
          {
            required: true,
            message: this.$t("仓库名称不能为空"),
            trigger: "blur",
          },
        ],
        titleEn: [
          {
            required: true,
            message: this.$t("英文名称不能为空"),
            trigger: "blur",
          },
        ],
        head: [
          {
            required: true,
            message: this.$t("负责人不能为空"),
            trigger: "blur",
          },
        ],
        tell: [
          {
            required: true,
            message: this.$t("联系电话不能为空"),
            trigger: "blur",
          },
        ],
        volume: [
          { required: true, message: this.$t("容量不能为空"), trigger: "blur" },
        ],
        addressZh: [
          {
            required: true,
            message: this.$t("仓库地址不能为空"),
            trigger: "blur",
          },
        ],
        addressEn: [
          {
            required: true,
            message: this.$t("英文地址不能为空"),
            trigger: "blur",
          },
        ],
        tradeType: [
          {
            required: true,
            message: this.$t("请选择网点属性"),
            trigger: "change",
          },
        ],
        checkList: [
          {
            type: "array",
            required: true,
            message: this.$t("请至少选择一个服务内容"),
            trigger: "change",
          },
        ],
      },
      nodeId: this.$route.query.nodeId,
      // 枚举
      CommonStatusEnum: CommonStatusEnum,
      // 数据字典
      statusDictDatas: getDictDatas(DICT_TYPE.COMMON_STATUS),
      regionTypeDatas: getDictDatas(DICT_TYPE.ECW_REGION_TYPE),
      transportDatas: getDictDatas(DICT_TYPE.ECW_TRANSPORT_TYPE),
      kycDatas: getDictDatas(DICT_TYPE.ECW_KYC_DATA),
    };
  },

  computed: {
    checkedFn() {
      return (val) => {
        return (
          Array.isArray(this.lineform.otherService)
            ? this.lineform.otherService
            : []
        ).includes(val);
      };
    },
    DICT_TYPE() {
      return DICT_TYPE;
    },
    getDictDataL() {
      return getDictDataL;
    },
    isShowError() {
      return (item) => {
        if (item.id !== "5" && item.id !== "10") return true;
        const { otherService } = this.lineform;
        if ((Array.isArray(otherService) ? otherService : []).includes("2"))
          return true;
        return false;
      };
    },
    transportName() {
      return (transportType) => {
        for (let index in this.transportDatas) {
          let transportItem = this.transportDatas[index];
          if (transportItem.value == transportType) {
            return this.$l(transportItem, "label");
          }
        }
      };
    },

    transportNames() {
      return (freight) => {
        let transportTypes = freight.split(",");
        let names = [];
        for (let index in transportTypes) {
          let transportType = transportTypes[index];
          let name = this.transportName(transportType);
          if (name) names.push(name);
        }
        return names.join(",");
      };
    },

    tradeTypeName() {
      return (tradeType) => {
        for (let index in this.regionTypeDatas) {
          let regionTypeItem = this.regionTypeDatas[index];
          if (regionTypeItem.value == tradeType) {
            return this.$l(regionTypeItem, "label");
          }
        }
      };
    },

    serviceNames() {
      return (otherService) => {
        if (!otherService) return "";
        let serviceList = Array.isArray(otherService)
          ? otherService
          : otherService.split(",");
        let names = [];
        const serviceGroup = this.serviceGroup.concat(this.endServiceGroup);
        for (let index in serviceList) {
          let item = serviceList[index];
          for (let dictIndex in serviceGroup) {
            let dictItem = serviceGroup[dictIndex];
            if (dictItem.id == item) {
              names.push(dictItem.text);
            }
          }
        }
        return names.join(",");
      };
    },
  },

  watch: {
    "form.zhou"(newV, oldV) {
      if (oldV && oldV != newV) {
        this.form.guojia = null;
        this.form.sheng = null;
        this.form.shi = null;
      }
    },

    "form.guojia"(newV, oldV) {
      if (oldV && oldV != newV) {
        this.form.sheng = null;
        this.form.shi = null;
      }
    },

    "form.sheng"(newV, oldV) {
      if (oldV && oldV != newV) {
        this.form.shi = null;
      }
    },
  },

  created() {
    getCurrencyPage(this.params).then(
      (res) => (this.currencyList = res.data.list)
    );
    if (this.nodeId) {
      this.queryParams.nodeId = parseInt(this.nodeId);
    }
    this.getList();
    this.getNodeList();
    this.getContinentsList();
  },
  methods: {
    getDictDataLabel,
    modifyAmountUnit(val) {
      if (val === 6) {
        this.lineform.minPrice = 900;
      } else if (val === 3) {
        this.lineform.minPrice = 10;
      } else {
        this.lineform.minPrice = 2;
      }
    },
    changeOtherService(val) {
      if (
        val === "2" &&
        !(
          Array.isArray(this.lineform.otherService)
            ? this.lineform.otherService
            : []
        ).includes("10")
      ) {
        this.lineform.otherService.push("10");
      }
    },
    getDictDatas,
    setTpl(type) {
      this.ladingform.titleZh = tpl[type];
    },
    setAgreementTpl(type) {
      this.ladingform.contentZh = tpl[type];
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 处理查询参数
      let params = { ...this.queryParams };
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, "createTime");
      // 执行查询
      getWarehousePage(params).then((response) => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },

    delRow(index) {
      this.arr.splice(index, 1);
    },
    ladingFormClose() {
      this.resetTemplate();
    },
    handleAddAccount() {
      const obj = { detail: "", name: "", company: "" };
      this.arr.push(obj);
    },
    /** 查询部门列表 */
    getDeptList() {
      listDept(this.queryParams).then((response) => {
        this.deptList = this.handleTree(response.data, "id");
        //回选已选择的部门
        this.recoveryChecked();
      });
    },

    recoveryChecked() {
      for (let index in this.deptList) {
        let dept = this.deptList[index];
        this.deptChecked(dept);
      }
    },

    deptChecked(dept) {
      let deptIdList = this.deptWarhouse.deptIdList;
      // console.log(deptIdList);
      const hasSelect = deptIdList.some((el) => {
        return dept.id === el;
      });
      if (hasSelect) {
        this.toggleSelection(dept, true);
      }
      if (dept.children) {
        dept.children.map((j) => {
          this.deptChecked(j);
        });
      }
    },

    // 用户昵称展示
    userNicknameFormat(row, column) {
      if (!row.leaderUserId) {
        return this.$t("未设置");
      }
      for (let index in this.users) {
        let user = this.user[index];
        if (row.leaderUserId === user.id) {
          return user.nickname;
        }
      }
      return this.$t("未知") + this.$t("【") + row.leaderUserId + this.$t("】");
    },

    /** 绑定部门 */
    bindDept(row) {
      this.deptWarhouse = row;
      this.deptOpen = true;
      this.getDeptList();
    },

    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },

    getSelectNode(nodeId) {
      for (let index in this.nodeList) {
        let node = this.nodeList[index];
        if (node.id == nodeId) return node;
      }
    },

    // 覆盖默认的上传行为
    requestUpload() {},
    // 上传预处理
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.$modal.msgError(
          this.$t("文件格式错误,请上传图片类型,如:JPG,PNG后缀的文件。")
        );
      } else {
        //上传
        let formData = new FormData();
        formData.append("file", file);
        // formData.append("path", this.uuid());
        uploadFile(formData).then((response) => {
          this.$set(this.form, "img", response.data);
          // this.form.img = response.data;
        });
      }
    },

    uuid() {
      var s = [];
      var hexDigits = "0123456789abcdef";
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = "-";

      var uuid = s.join("");
      return uuid;
    },

    getContinentsList() {
      this.queryParams.treeType = 0;
      getListTree(this.queryParams).then((response) => {
        this.continentsList = response.data;
      });
    },

    templateClick(row) {
      if (row != "") {
        getLadingTemplate(row.lineId).then((response) => {
          if (response.data != null) {
            this.ladingform = response.data;
            var jsonArr = JSON.parse(response.data.account);
            for (var i in jsonArr) {
              this.arr.push(jsonArr[i]);
            }
          }
        });
        this.ladingform.lineId = row.lineId;
      } else {
        this.showFlag = true;
      }
      this.templateOpen = true;
    },

    serviceClick(row) {
      if (this.routeQueryParam.tradeType == 1) {
        this.destName = this.$l(row, "title");
      } else {
        this.startName = this.$l(row, "title");
      }
      if (row.otherService) {
        this.lineform.otherService = Array.isArray(row.otherService)
          ? row.otherService
          : row.otherService?.split(",") ?? [];
      } else {
        this.lineform.otherService = [];
      }
      this.serviceOpen = true;
      this.lineform.lineId = row.lineId;
      this.lineform.transportType = row.transportType;
      this.lineform.isClientShow = row.isClientShow ? 1 : 0;

      this.lineform.makeBillNode = row.makeBillNode || "6";
      this.lineform.currencyUnit = row.currencyUnit ? row.currencyUnit : 1;
      this.lineform.controlStatus = row.controlStatus ? row.controlStatus : 0;
      this.lineform.tempTitleZh = row.tempTitleZh;
      this.lineform.tempTitleEn = row.tempTitleEn;
      this.lineform.lkLeft=row.lkLeft;
      this.lineform.lkRight=row.lkRight; //lanbm 2024-06-10 add
      this.lineform.tzName=row.tzName; //图章配置参数 lanbm 2024-06-12 add
      // 先清空 发货人和收货人信息
      this.lineform.senderInfo = {
        companyAddress: "",
        companyAddressEn: "",
        name: "",
        nameEn: "",
      };
      this.lineform.recipientInfo = {
        companyAddress: "",
        companyAddressEn: "",
        name: "",
        nameEn: "",
      };
      Object.assign(this.lineform.recipientInfo, row.recipientInfo);
      Object.assign(this.lineform.senderInfo, row.senderInfo);
      this.lineform.minPrice = row.minPrice ? row.minPrice : 0;
      if (row.minPrice) {
        this.lineform.minPrice = row.minPrice;
      } else {
        if (this.lineform.currencyUnit === 6) {
          this.lineform.minPrice = 900;
        } else if (this.lineform.currencyUnit === 3) {
          this.lineform.minPrice = 10;
        } else {
          this.lineform.minPrice = 2;
        }
      }

      console.log(row, "row");
    },

    submitLineForm() {
      //ecw_warehouse_line
      let otherService = this.lineform.otherService;
      // 如果不存在送货上门,则过滤提货异常
      if (!otherService.includes("2")) {
        otherService = otherService.filter((id) => id !== "5");
      }
      serviceConfig({
        lineId: this.lineform.lineId,
        otherService: otherService.join(","),
        isClientShow: this.lineform.isClientShow,
        makeBillNode: this.lineform.makeBillNode,
        controlStatus: this.lineform.controlStatus,
        currencyUnit: this.lineform.currencyUnit,
        minPrice: this.lineform.minPrice,
        senderInfo: this.lineform.senderInfo,
        recipientInfo: this.lineform.recipientInfo,
        tempTitleZh: this.lineform.tempTitleZh,
        tempTitleEn: this.lineform.tempTitleEn,
        lkLeft: this.lineform.lkLeft,
        lkRight: this.lineform.lkRight, //lanbm 2024-06-10 add
        tzName: this.lineform.tzName, //图章配置参数 lanbm 2024-06-12 add
      }).then((res) => {
        this.$modal.msgSuccess(this.$t("操作成功"));
        this.getRouteList();

        for (let index in this.routeList) {
          let routeItem = this.routeList[index];
          if (routeItem.lineId && routeItem.lineId == this.lineform.lineId) {
            // routeItem.otherService = otherService;
            this.$set(routeItem, "otherService", otherService);
          }
        }
        this.serviceOpen = false;
      });
    },

    routeStatusClick(row) {
      this.routeQueryParam.transportType = row.transportType;
      this.routeQueryParam.warehouseId = row.id;
      this.routeQueryParam.lineId = row.lineId;
      changeRouteStatus(this.routeQueryParam).then((response) => {
        let lineId = response.data;
        this.$set(row, "lineId", lineId);
        row.lineId = lineId;
        this.$modal.msgSuccess("操作成功");
      });
    },

    toRouteList(row, tradeType) {
      this.routeQueryParam.id = row.id;
      this.routeQueryParam.tradeType = tradeType;
      this.routeQueryParam.pageNo = 1;
      this.showRouteList = true;
      this.routeLoadig = true;
      if (tradeType == 1) {
        this.startName = row.titleZh;
      } else {
        this.destName = row.titleZh;
      }
      this.getRouteList();
    },

    getRouteList() {
      routerList(this.routeQueryParam).then((response) => {
        this.routeList = response.data.list;
        this.routeCount = response.data.total;
        this.routeLoadig = false;
      });
    },

    //获取网点列表
    getNodeList() {
      let params = { pageNo: 1, pageSize: 100 };
      getNodePage(params).then((response) => {
        this.nodeList = response.data.list;
      });
    },

    changeContinents(zhou) {
      for (let index in this.continentsList) {
        let continent = this.continentsList[index];
        if (continent.id == zhou) {
          this.countryList = continent.children;
          return;
        }
      }
    },
    changeCountry(countryId) {
      for (let index in this.countryList) {
        let country = this.countryList[index];
        if (country.id == countryId) {
          this.provinceList = country.children;
          return;
        }
      }
    },
    changeProvince(provinceId) {
      for (let index in this.provinceList) {
        let province = this.provinceList[index];
        if (province.id == provinceId) {
          this.cityList = province.children;
          return;
        }
      }
    },

    changeCity(cityId) {
      for (let index in this.cityList) {
        let city = this.cityList[index];
        if (city.id == cityId) {
          return;
        }
      }
    },

    handleStatusChange(row) {
      let text =
        row.status === CommonStatusEnum.ENABLE
          ? this.$t("启用")
          : this.$t("停用");
      this.$modal
        .confirm(
          this.$t("确认要{action}编号为{id}的数据吗?", {
            action: text,
            id: row.id,
          })
        )
        .then(function () {
          return updateWarehouse(row);
        })
        .then(() => {
          this.$modal.msgSuccess(text + " " + this.$t("成功"));
        })
        .catch(function () {
          row.status =
            row.status === CommonStatusEnum.ENABLE
              ? CommonStatusEnum.DISABLE
              : CommonStatusEnum.ENABLE;
        });
    },

    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    resetTemplate() {
      this.arr = [];
      this.showFlag = false;
      this.ladingform = {
        prefixCounter: undefined,
        titleZh: undefined,
        account: undefined,
        contentZh: undefined,
      };
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        pid: undefined,
        number: undefined,
        qianzhui: undefined,
        titleZh: undefined,
        titleEn: undefined,
        volume: undefined,
        addressZh: undefined,
        addressEn: undefined,
        zhou: undefined,
        guojia: undefined,
        sheng: undefined,
        shi: undefined,
        head: undefined,
        tell: undefined,
        tradeType: undefined,
        freight: undefined,
        remark: undefined,
        sort: undefined,
        status: undefined,
        img: undefined,
        checkList: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isUpdate = false;
      if (this.nodeId) {
        //把已现在的网点的一些属性赋值给仓库
        this.form.nodeId = this.queryParams.nodeId;
        let node = this.getSelectNode(this.form.nodeId);
        this.form.zhou = node.zhou;
        this.form.guojia = node.guojia;
        this.form.sheng = node.sheng;
        this.form.shi = node.shi;
        this.form.tradeType = node.tradeType;

        this.form.checkList = node.freight.split(",");

        this.changeContinents(this.form.zhou);
        this.changeCountry(this.form.guojia);
        this.changeProvince(this.form.sheng);
      }
      this.open = true;
      this.title = this.$t("添加仓库");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getWarehouse(id).then((response) => {
        this.form = response.data;

        let ckList = response.data.freight.split(",");
        this.$set(this.form, "checkList", ckList);

        this.changeContinents(response.data.zhou);
        this.changeCountry(response.data.guojia);
        this.changeProvince(response.data.sheng);
        this.isUpdate = true;
        this.open = true;
        this.title = this.$t("修改仓库");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }

        //逗号拼接运输方式
        var freight = "";
        for (let i = 0; i < this.form.checkList.length; i++) {
          freight += this.form.checkList[i] + ",";
        }
        freight = freight.substring(0, freight.length - 1);
        this.form.freight = freight;

        // 修改的提交
        if (this.form.id != null) {
          updateWarehouse(this.form).then((response) => {
            this.$modal.msgSuccess(this.$t("修改成功"));
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createWarehouse(this.form).then((response) => {
          this.$modal.msgSuccess(this.$t("新增成功"));
          this.open = false;
          this.getList();
        });
      });
    },

    submitTemplateForm() {
      if (this.showFlag && this.ladingform.lineIds != null) {
        let lineId = "";
        let lineArr = this.ladingform.lineIds;
        lineArr.forEach((elem, index) => {
          lineId = lineId + elem.lineId + ",";
        });
        this.ladingform.lineId = lineId.substr(0, lineId.length - 1);
      }
      this.ladingform.account = JSON.stringify(this.arr);
      createTemplate(this.ladingform).then((response) => {
        this.$modal.msgSuccess(this.$t("设置路线提单模板成功"));
        this.templateOpen = false;
        this.resetTemplate();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal
        .confirm(this.$t("是否确认删除仓库编号为{id}的数据项?", { id }))
        .then(function () {
          return deleteWarehouse(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t("删除成功"));
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = { ...this.queryParams };
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.addBeginAndEndTime(params, this.dateRangeCreateTime, "createTime");
      // 执行导出
      this.$modal
        .confirm(this.$t("是否确认导出所有仓库数据项?"))
        .then(() => {
          this.exportLoading = true;
          return exportWarehouseExcel(params);
        })
        .then((response) => {
          this.$download.excel(response, "${table.classComment}.xls");
          this.exportLoading = false;
        })
        .catch(() => {});
    },

    /**提交绑定部门 */
    commitBind() {
      if (!this.selectDeptList || this.selectDeptList.length == 0) {
        this.$message.error(this.$t("请先选择部门"));
        return;
      }
      //获取部门id列表
      let deptIdList = [];
      this.selectDeptList.map((item) => {
        deptIdList.push(item.id);
        return item;
      });
      let params = {
        deptIdList: deptIdList,
        warehouseId: this.deptWarhouse.id,
      };
      deptBind(params).then((response) => {
        this.$message.success(this.$t("绑定成功"));
        let deptIdList = response.data;
        // console.log(deptIdList);

        for (let index in this.list) {
          let warehouse = this.list[index];
          if (warehouse.id == this.deptWarhouse.id) {
            warehouse.deptIdList = deptIdList;
          }
        }
        // console.log(this.list);
        this.deptOpen = false;
      });
    },

    handleSelectionChange(value) {
      this.selectDeptList = value;
      // console.log(this.selectDeptList);
    },

    setChildren(children, type) {
      // 编辑多个子层级
      children.map((j) => {
        this.toggleSelection(j, type);
        if (j.children) {
          this.setChildren(j.children, type);
        }
      });
    },

    // 选中父节点时,子节点一起选中取消
    select(selection, row) {
      const hasSelect = selection.some((el) => {
        return row.id === el.id;
      });
      if (hasSelect) {
        if (row.children) {
          // 解决子组件没有被勾选到
          this.setChildren(row.children, true);
        }
        //TODO  判断父节点的所有子节点是否都被选中
      } else {
        //TODO  取消选择判断父节点的所有子节点是否都被取消
        if (row.children) {
          this.setChildren(row.children, false);
        }
      }
    },
    toggleSelection(row, select) {
      if (row) {
        this.$nextTick(() => {
          this.$refs.multipleTable &&
            this.$refs.multipleTable.toggleRowSelection(row, select);
        });
      }
    },

    // 选择全部
    selectAll(selection) {
      // console.log(selection);
      // tabledata第一层只要有在selection里面就是全选
      const isSelect = selection.some((el) => {
        const tableDataIds = this.deptList.map((j) => j.id);
        return tableDataIds.includes(el.id);
      });
      // tableDate第一层只要有不在selection里面就是全不选
      const isCancel = !this.deptList.every((el) => {
        const selectIds = selection.map((j) => j.id);
        return selectIds.includes(el.id);
      });
      if (isSelect) {
        selection.map((el) => {
          if (el.children) {
            // 解决子组件没有被勾选到
            this.setChildren(el.children, true);
          }
        });
      }
      if (isCancel) {
        this.deptList.map((el) => {
          if (el.children) {
            // 解决子组件没有被勾选到
            this.setChildren(el.children, false);
          }
        });
      }
    },
  },
};
</script>