<template>
  <basic-container>
    <div class="avue-crud">
      <el-row v-if="!search">
        <!-- 查询模块 -->
        <el-form :inline="true" :model="query"  class='fr-fo'>
          <div>
          <el-form-item label="客户名称:">
            <el-input v-model="query.clientName" placeholder="请输入客户名称"></el-input>
          </el-form-item>
          <el-form-item label="客户类型:">
            <!--            <el-input v-model="query.typeService" placeholder="请输入客户类型;1 C端  2 B端"></el-input>-->
            <el-select v-model="query.clientType" class="m-2" placeholder="请选择客户端类型">
              <el-option
                v-for="item in clientType"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="地址:">
            <!--            <el-input v-model="query.bladeRegionProvinceId" placeholder="请输入省份"></el-input>-->
            <el-cascader :options="optioner" v-model="query.bladeRegionProvinceId">
              <template #default="{ node, data }">
                <span>{{ data.label }}</span>
                <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
              </template>
            </el-cascader>
          </el-form-item>

          <!--          <el-form-item label="市:">-->
          <!--            <el-input v-model="query.bladeRegionCityId" placeholder="请输入市"></el-input>-->

          <!--          </el-form-item>-->
          <!--          <el-form-item label="区/县:">-->
          <!--            <el-input v-model="query.bladeRegionAreaId" placeholder="请输入区/县"></el-input>-->
          <!--            -->
          <!--          </el-form-item>-->
          <el-form-item label="合同开始时间:" class='el-times'>
            <!--            <el-input v-model="query.contractStartTime" placeholder="请输入合同开始时间"></el-input>-->
            <div class="block">
              <!--              <span class="demonstration">With quick options</span>-->
              <el-date-picker
                v-model="dataShi"
                type="daterange"
                unlink-panels
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :shortcuts="shortcuts"
                :size="'default'"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </div>
          </el-form-item>
          <!--          <el-form-item label="合同结束时间:">-->
          <!--            <el-input v-model="query.contractEntTime" placeholder="请输入合同结束时间"></el-input>-->
          <!--          </el-form-item>-->
          </div>
          <!-- 查询按钮 -->
          <el-form-item class='el-btn'>
            <el-button type="primary" icon="el-icon-search" @click="searchChange">搜 索</el-button>
            <el-button icon="el-icon-delete" @click="searchReset()">清 空</el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <el-row>
        <div class="avue-crud__header">
          <!-- 头部左侧按钮模块 -->
          <div class="avue-crud__left">
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新 增</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="handleDelete" plain >删 除</el-button >
            <el-button type="danger"  icon="el-icon-delete"   @click="handleImport">导 入 </el-button>
          </div>
          <!-- 头部右侧按钮模块 -->
          <div class="avue-crud__right">
            <el-button icon="el-icon-refresh" @click="searchChange" circle></el-button>
            <el-button icon="el-icon-search" @click="searchHide" circle></el-button>
          </div>
        </div>
      </el-row>
      <el-row>
        <tablecmt
          :columnList="columnList"
          :tableData="data"
          :loading="loading"
          @inputTxt="inputsc"
          @timeCheck="timesc"
          @btnCheck="btnsc"
          @selectCheck="selectsc"
          @selection="selectionChange"
          @makeCargo="makeCargo"
        >
          <template #default="slotProps">
            <el-text
              type="primary"
              text
              icon="el-icon-view"
              @click="handleView(slotProps.scope.row)"
              >查看</el-text
            >
            <el-text
              type="primary"
              text
              icon="el-icon-edit"
              @click="handleEdit(slotProps.scope.row)"
              >编辑</el-text
            >
            <el-text type="primary" text icon="el-icon-delete" @click="rowDel(slotProps.scope.row)"
              >删除</el-text
            >
            <!-- <el-text type="primary" text icon="el-icon-delete" @click="handleAddSon(slotProps.scope.row)">新增</el-text>
              <el-text type="primary" text icon="el-icon-delete" @click="handleHistory(slotProps.scope.row)">合同历史记录</el-text>
              <el-text type="primary" text icon="el-icon-delete" @click="handleEntrepot(slotProps.scope.row)">服务仓</el-text>
              <el-text type="primary" text icon="el-icon-delete" @click="handleLinkman(slotProps.scope.row)">联系人</el-text>
              <el-text type="primary" text icon="el-icon-delete" @click="handleBrand(slotProps.scope.row)">品牌</el-text>
              <el-text type="primary" text icon="el-icon-delete" @click="handleMall(slotProps.scope.row)">三方商城</el-text> -->
            <el-dropdown @command="command => handleCommand(command, slotProps.scope.row)">
              <el-text type="primary" text>
                更多
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </el-text>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="1">
                    <el-text>新增</el-text>
                  </el-dropdown-item>
                  <el-dropdown-item command="2">
                    <el-text>合同历史记录</el-text>
                  </el-dropdown-item>
                  <el-dropdown-item command="3">
                    <el-text>服务仓</el-text>
                  </el-dropdown-item>
                  <el-dropdown-item command="4">
                    <el-text>联系人</el-text>
                  </el-dropdown-item>
                  <el-dropdown-item command="5">
                    <el-text>品牌</el-text>
                  </el-dropdown-item>
                  <el-dropdown-item command="6">
                    <el-text>三方商城</el-text>
                  </el-dropdown-item>
                  <el-dropdown-item command="7">
                    <el-text>开通账号</el-text>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </tablecmt>
        <!-- 列表模块 -->
      </el-row>
      <el-row>
        <div class="avue-crud__pagination flex-c-sb" style="width:100%;">
          <div style="font-size: 14px;">
            勾选数量: {{ selectionList.length }}
          </div>
          <!-- 分页模块 -->
          <el-pagination align="right"
                         background
                         @size-change="sizeChange"
                         @current-change="currentChange"
                         :current-page="page.currentPage"
                         :page-sizes="[30, 50,80, 120]"
                         :page-size="page.pageSize"
                         layout="total, sizes, prev, pager, next, jumper"
                         :total="page.total">
          </el-pagination>
        </div>
      </el-row>
      <el-dialog title="客户导入" append-to-body v-model="excelBox" width="555px">
        <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
          <template #excelTemplate>
            <el-button type="primary" @click="handleTemplate">
              <a href="http://192.168.10.100:9000/htlogpm/upload/20231024/ac94acebf315f1f3625e8633800e290c.xlsx" download="客户模板.xlsx">
                点击下载<i class="el-icon-download el-icon--right"></i>
              </a>
            </el-button>

          </template>
        </avue-form>
      </el-dialog>
      <!-- 表单模块 -->
      <el-dialog
        :title="title"
        v-model="box"
        width="40%"
        :before-close="beforeClose"
        :close-on-click-modal="false"
        append-to-body
      >
        <el-form :disabled="view" ref="form" :model="form" :rules="rules" label-width="120px">
          <!-- 表单字段 -->
          <el-form-item label="客户编码" prop="clientCode">
            <el-input
              v-model="form.clientCode"
              :validate-method="validateInput"
              placeholder="请输入客户编码"
              style="width: 100%"
              :disabled="viewClientEntd"
            />
          </el-form-item>
          <el-form-item label="客户名称" prop="clientName">
            <el-input v-model="form.clientName" placeholder="请输入客户名称" style="width: 100%" />
          </el-form-item>
          <el-form-item label="客户类型" prop="clientType">
            <!--            <el-input v-model="form.clientName" placeholder="请输入客户名称"  style="width: 100%"/>-->
            <!--            <el-select v-model="form.clientType" class="m-2" placeholder="请选择客户类型" style="width: 100%">-->
            <!--              <el-option label="发货方" value="1"/>-->
            <!--              <el-option label="收货方" value="2"/>-->
            <!--            </el-select>-->
            <el-select
              v-model="form.clientType"
              class="m-2"
              placeholder="请选择客户端类型"
              style="width: 100%"
            >
              <el-option
                v-for="item in clientType"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="服务类型" prop="typeServiceList">
            <el-select
              v-model="form.typeServiceList"
              multiple
              placeholder="请选择"
              style="width: 100%"
              @change="coverCharge"
            >
              <el-option
                v-for="item in freightType"
                :key="item.dictKey"
                :label="item.dictValue"
                :value="item.dictKey"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="配送类型" prop="businessType" v-if="distriType">
            <el-radio-group
              v-model="form.businessType"
              class="ml-4"
              v-for="item in distributionType"
            >
              <el-radio :label="item.dictKey" size="large" style="margin-right: 25px">{{
                item.dictValue
              }}</el-radio>
              <!--                  <el-radio label="2" size="large">Option 2</el-radio>-->
            </el-radio-group>
            <!--              </div>-->
          </el-form-item>
          <!--                    <el-form-item label="客户端类型" prop="typeService">
          &lt;!&ndash;            <el-input v-model="form.typeService" placeholder="请输入客户类型"/>&ndash;&gt;
          &lt;!&ndash;            <el-input v-model="form.typeService" placeholder="请输入客户类型;1 C端  2 B端"/>&ndash;&gt;
                      <el-select v-model="form.typeService" class="m-2" placeholder="请选择客户端类型" style="width: 100%">
                        <el-option
                          v-for="item in clientType"
                          :key="item.dictKey"
                          :label="item.dictValue"
                          :value="item.dictKey"

                        />
                      </el-select>
                    </el-form-item>-->
          <el-form-item label="联系人" prop="linkman" v-if="viewEntd">
            <el-input v-model="form.linkman" placeholder="请输入联系人" style="width: 100%" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone" v-if="viewEntd">
            <el-input v-model="form.phone" placeholder="请输入联系电话" style="width: 100%" />
          </el-form-item>
          <el-form-item label="地址" prop="bladeRegionProvinceId">
            <!--            <el-input v-model="form.bladeRegionProvinceId" placeholder="请输入省份"/>-->
            <el-cascader
              :options="optioner"
              style="width: 100%"
              v-model="form.bladeRegionProvinceId"
            >
              <template #default="{ node, data }">
                <span>{{ data.label }}</span>
                <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
              </template>
            </el-cascader>
          </el-form-item>
          <el-form-item label="详细地址" prop="detailedly">
            <el-input v-model="form.detailedly" placeholder="请填写详细地址" style="width: 100%" />
          </el-form-item>
          <!--          <el-form-item label="三方商城" prop="tripartiteMall">-->
          <!--            <el-input v-model="form.tripartiteMall" placeholder="请填写三方商城" style="width: 100%" />-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="开票信息" prop="billingInformation">-->
          <!--            <el-input v-model="form.billingInformation" placeholder="请填写开票信息" style="width: 100%" />-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="市" prop="bladeRegionCityId">-->
          <!--            <el-input v-model="form.bladeRegionCityId" placeholder="请输入市"/>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="区/县" prop="bladeRegionAreaId">-->
          <!--            <el-input v-model="form.bladeRegionAreaId" placeholder="请输入区/县"/>-->
          <!--          </el-form-item>-->
          <el-form-item label="合同附件" prop="leaseAccessories" style="width: 100%">
            <!--            <el-input v-model="form.leaseAccessories" placeholder="请输入合同附件"/>-->
            <el-upload
              v-model:file-list="fileList"
              class="upload-demo"
              :action="action"
              :headers="headers"
              multiple
              :on-preview="handlePreview"
              :on-success="
                (response, file, fileList) => {
                  uploadSuccess(fileList);
                }
              "
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :before-upload="beforeUploadFn"
              :limit="3"
              :on-exceed="handleExceed"
            >
              <el-button>上传</el-button>
              <template #tip>
                <div class="el-upload__tip">大小不超过500KB的jpg/png文件。</div>
              </template>
            </el-upload>
            <el-image-viewer
              v-if="showImgViewer"
              :url-list="imgPreviewUrl"
              @close="handleCo"
              :z-index="300"
              fit="cover"
            />
          </el-form-item>
          <el-form-item label="合同开始时间" prop="contractStartTime" label-width="120px">
            <!--            <el-input v-model="form.contractStartTime" placeholder="请输入合同开始时间"/>-->
            <div class="demo-date-picker" style="width: 60%">
              <div class="block">
                <!--                <span class="demonstration">Default</span>-->
                <el-date-picker
                  v-model="form.contractStartTime"
                  type="date"
                  placeholder="选择时间"
                  format="YYYY/MM/DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </div>
            </div>
          </el-form-item>

          <el-form-item label="合同结束时间" prop="contractEntTime" label-width="120px">
            <!--            <el-input v-model="form.contractEntTime" placeholder="请输入合同结束时间"/>-->
            <div class="demo-date-picker">
              <div class="block">
                <!--                <span class="demonstration">Default</span>-->
                <el-date-picker
                  v-model="form.contractEntTime"
                  type="date"
                  placeholder="选择时间"
                  format="YYYY/MM/DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </div>
            </div>
          </el-form-item>
        </el-form>
        <!-- 表单按钮 -->
        <template #footer>
          <span v-if="!view" class="dialog-footer">
            <el-button type="primary" icon="el-icon-circle-check" @click="handleSubmit('form')"
              >提 交</el-button
            >
            <el-button icon="el-icon-circle-close" @click="box = false">取 消</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 账号绑定弹出框页面
      1、显示登录账号
      2、显示账号的名称 -->
      <el-dialog title="开通账号" v-model="openAcountStatus">
        <el-form
          :disabled="view"
          ref="openAcountorm"
          :model="openAcountform"
          :rules="openAcountrules"
          label-width="120px"
        >
          <el-form-item label="姓名" prop="linkman">
            <el-input
              v-model="openAcountform.name"
              placeholder="请输入联系人"
              maxlength="20"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="账号" prop="linkman">
            <el-input
              v-model="openAcountform.phone"
              placeholder="请输入电话"
              type="number"
              maxlength="11"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="密码">
            <span style="color: red">默认系统初始化密码</span>
          </el-form-item>
        </el-form>

        <template #footer>
          <span v-if="!view" class="dialog-footer">
            <el-button type="primary" icon="el-icon-circle-check" @click="handleSubmit('form')"
              >提 交</el-button
            >
            <el-button icon="el-icon-circle-close" @click="openAcountStatus = false"
              >取 消</el-button
            >
          </span>
        </template>
      </el-dialog>

      <el-drawer
        title="子表操作"
        append-to-body
        size="60%"
        v-model="drawer"
        :direction="direction"
        :before-close="handleDrawerClose"
      >
        <BasicShopSub :mainId="basicClientId"></BasicShopSub>
      </el-drawer>
      <!--      <el-drawer-->
      <!--        title="历史记录"-->
      <!--        append-to-body-->
      <!--        size="60%"-->
      <!--        v-model="drawer"-->
      <!--        :direction="direction"-->
      <!--        :before-close="handleDrawerClose">-->
      <!--        <BasicShopSub :mainId="basicClientId"></BasicShopSub>-->
      <!--      </el-drawer>-->
    </div>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  updateCargoControl,
  remove,
  getListCode,
} from '@/api/basicdata/basicClient';
import option from '@/option/basicdata/basicClient';
import { mapGetters } from 'vuex';
import BasicShopSub from '@/views/basicdata/brand/basicShopSub.vue';
import { getDictionaryBiz } from '@/api/system/dict';
import { getSelect, getLazyTree, getLazyList, getLazyTreeAll } from '@/api/base/region';
import { getToken } from '@/utils/auth';
import globalc from '@/api/basicdata/globalc';
import { Base64 } from 'js-base64';
import dayjs from 'dayjs';
import { exportBlob } from '@/api/common';
import { downloadXls } from '@/utils/util';

export default {
  components: {
    BasicShopSub,
  },
  data() {
    return {
      excelForm: {},
      excelBox: false,
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '文件上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '文件上传，请稍等',
            span: 24,
            propsHttp: {
              res: 'data',
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: '/api/logpm-basicdata/basicdataClient/import-basicDataClient',
          }
          ,
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          },
        ],
      },
      columnList: [
        {
          prop: '',
          label: '全选',
          type: 0,
          values: '',
          width: 55,
          checkarr: [],
          fixed: true,
        },
        {
          prop: 'clientName',
          label: '客户名称',
          type: 2,
          values: '',
          width: '130',
          checkarr: [],
          fixed: false,
          sortable: true,
          head: false,
        },
        {
          prop: 'clientCode',
          label: '客户编码',
          type: 2,
          values: '',
          width: '130',
          checkarr: [],
          fixed: false,
          sortable: true,
          head: false,
        },
        {
          prop: 'clientTypeName',
          label: '客户类型',
          type: 3,
          values: '',
          width: '130',
          checkarr: [],
          fixed: false,
          sortable: true,
          head: false,
        },
        {
          prop: 'typeServiceName',
          label: '服务类型',
          type: 1,
          values: '',
          width: '130',
          checkarr: [],
          fixed: false,
          sortable: true,
        },
        {
          prop: 'bladeRegionProvinceId',
          label: '地址',
          type: 2,
          values: '',
          width: '200',
          checkarr: [],
          fixed: false,
          sortable: true,
        },
        {
          prop: 'fileName',
          label: '合同附件',
          type: 9,
          values: '',
          width: '180',
          checkarr: [],
          fixed: false,
          sortable: true,
          downprop: 'leaseAccessories',
        },
        {
          prop: 'cargoControl',
          label: '控货',
          type: 11,
          values: '',
          width: '100',
          checkarr: [
            // {value:false,label:'否'},
            // {value:true,label:'是'},
          ],
          fixed: false,
          sortable: true,
        },
        {
          prop: 'contractStartTime',
          label: '合同开始时间',
          type: 5,
          values: '',
          width: '150',
          checkarr: [],
          fixed: false,
          sortable: true,
        },
        {
          prop: 'contractEntTime',
          label: '合同结束时间',
          type: 5,
          values: '',
          width: '150',
          checkarr: [],
          fixed: false,
          sortable: true,
          head: false,
        },
        {
          prop: '',
          label: '操作',
          type: 6,
          values: '',
          width: '200',
          checkarr: [],
          fixed: 'right',
          hide: true,
        },
      ],
      columnListedit: [],
      activeNames: ['1'],
      height: 0,
      showImgViewer: false,
      imgPreviewUrl: [], // 当前要放大的图片存放位置
      fileList: [],

      // 主键
      basicClientId: '',
      // fileList:[], // 上传数据
      // 弹框标题
      title: '',
      // 是否展示弹框
      box: false,
      // 是否展示抽屉
      drawer: false,
      // 抽屉方向
      direction: 'rtl',
      // 是否显示查询
      search: true,
      // 加载中
      loading: true,
      // 是否为查看模式
      view: false,
      viewEntd: true,
      viewClientEntd: false,
      // 查询信息
      query: {},
      //查询时间
      dataShi: '',
      // 分页信息
      page: {
        currentPage: 1,
        pageSize: 30,
        total: 40,
      },

      // 表单数据
      form: {
        contractStartTime: '',
        contractEntTime: '',
      },
      // 选择行
      selectionList: [],
      testForm: {},
      // 表单配置
      option: option,
      // 表单列表
      data: [],
      clientType: [],
      freightType: [],
      optioner: [],
      distributionType: [],
      distriType: false, // 配送自提
      shortcuts: [
        {
          text: '上周',
          value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            return [start, end];
          },
        },
        {
          text: '上个月',
          value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            return [start, end];
          },
        },
        {
          text: '最近3个月',
          value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            return [start, end];
          },
        },
      ],
      rules: {
        clientCode: [
          { required: true, message: '请输入客户编码', trigger: 'blur' },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          { validator: this.validateInput, trigger: 'blur' },
        ],
        clientName: [
          { required: true, message: '请输入客户名称', trigger: 'blur' },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        typeService: [{ required: true, message: '请选择客户端类型', trigger: 'blur' }],
        businessType: [
          { required: true, message: '请选择配送业务类型', trigger: 'change' },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        clientType: [{ required: true, message: '请选择客户类型', trigger: 'change' }],
        typeServiceList: [{ required: true, message: '请选择服务类型', trigger: 'change' }],
        linkman: [{ required: true, message: '请填写联系人', trigger: 'blur' }],
        detailedly: [{ required: true, message: '请填写详细地址', trigger: 'blur' }],
        phone: [{ required: true, message: '请填写联系电话', trigger: 'blur' }],
        contractEntTime: [
          { type: 'date', required: true, message: '请选择合同结束时间', trigger: 'change' },
        ],
        contractStartTime: [
          { type: 'date', required: true, message: '请选择合同开始时间', trigger: 'change' },
        ],
        bladeRegionProvinceId: [{ required: true, message: '请选择地址', trigger: 'change' }],
        // leaseAccessories: [{ required: true, message: '请上传合同文件', trigger: 'blur' }],
      },
      bianji: false,

      openAcountStatus: false, //开通账号弹出框状态
      openAcountform: {
        name: '',
        phone: '',
      },
    };
  },
  created() {},
  mounted() {
    this.init();
  },
  computed: {
    ...mapGetters(['permission']),
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    // headers() {
    //   return {
    //     'Blade-Auth': 'Bearer ' + getToken(),
    //   };
    // },
    // action() {
    //   return '/api/blade-resource/oss/endpoint/put-file';
    //   // return '/api/blade-resource/oss/endpoint/put-file-attach'
    // },
  },
  methods: {
    uploadAfter(res, done, loading, column) {
      window.console.log(column);
      this.excelBox = false;
      // this.refreshChange();
      done();
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    handleImport() {
      this.excelBox = true;
    },
    handleTemplate() {

      // exportBlob(
      //   `/api/logpm-basicdata/basicdataClient/import-basicDataClient?${this.website.tokenHeader}=${getToken()}`
      // ).then(res => {
      //   downloadXls(res.data, '用户数据模板.xlsx');
      // });
    },
    showdrawer(value) {
      this.drawerShow = value;
    },
    /**
     * 弹窗的勾选回调，用于更改头部数组
     * 固定搭配，只需要更换   columnList
     */
    setnewcolum(newarr, headarr, type) {
      // console.log(newarr,'+++++++++++')
      if (type == 1) {
        this.columnList = newarr;
        this.$functions.setStorage(window.location.pathname + 'checkList', headarr);
      } else if (type == 2) {
        this.columnList = newarr;
        this.$functions.setStorage(window.location.pathname + 'flexList', headarr);
      } else if (type == 3) {
        this.columnList = newarr;
        this.$functions.setStorage(window.location.pathname + 'sortlist', headarr);
      }
    },
    selectionsc(value) {
      console.log(value);
    },
    delectsolt(scope) {
      const { row } = scope;
      console.log(row);
    },
    editsolt(scope) {
      const { row } = scope;
      console.log(row);
    },
    btnsc(index, row) {
      console.log(index, row);
    },
    selectsc(index, row) {
      console.log('123123123', index, row);
      if (row.prop === 'clientTypeName') {
        this.query['clientType'] = index;
      } else {
        this.query[row.prop] = index;
      }
      this.onLoad(this.page);
    },
    timesc(index, row) {
      console.log(index, row);
      if (!!index) {
        index = dayjs(index).format('YYYY-MM-DD');
      }
      this.query[row.prop] = index;
      if (!index) {
        delete this.query[row.prop];
      }
      this.onLoad(this.page);
    },
    inputsc(index, row) {
      console.log(index, row);
      // console.log(index, row.prop);
      this.query[row.prop] = index;
      this.onLoad(this.page);
    },

    handleCommand(command, row) {
      console.log(command, row);
      switch (Number(command)) {
        case 1:
          this.handleAddSon(row);
          break;
        case 2:
          this.handleHistory(row);
          break;
        case 3:
          this.handleEntrepot(row);
          break;
        case 4:
          this.handleLinkman(row);
          break;
        case 5:
          this.handleBrand(row);
          break;
        case 6:
          this.handleMall(row);
          break;
        case 7:
          this.openAcount(row);
          break;
      }
    },
    //远程校验
    validateInput(value, a) {
      // console.log("执行了",value,a);
      return new Promise((resolve, reject) => {
        // 发送异步请求到服务器进行校验
        // 假设请求返回的数据为 { valid: true } 表示校验通过
        // 模拟异步请求，假设延时1秒
        if (!this.viewClientEntd) {
          setTimeout(async () => {
            const response = { valid: false }; // 假设校验通过
            await getListCode({ code: a }).then(res => {
              // console.log("smgsmg",res.data);
              if (res.data.data.length > 0) {
                reject(new Error('编码已存在')); // 校验不通过，调用 reject() 并传递错误信息
              } else {
                resolve(); // 校验通过，调用 resolve()
              }
            });
          }, 1000);
        } else {
          resolve();
        }
      });
    },

    coverCharge(num) {
      this.distriType = false;
      // console.log(num);
      num.forEach(i => {
        if (i == '3') {
          this.distriType = true;
        }
      });
    },

    handleChange(val) {
      console.log(val);
    },

    /**
     * 开通账号
     */
    openAcount(row) {
      // this.openAcountform.name = row.linkman;
      // this.openAcountform.phone = row.phone;
      // this.openAcountStatus = true;

      this.$router.push({
        path: '/basicdata/brand/basicClientAccount',
        query: {
          id: row.id,
          name: '商场 - ' + row.clientName,
        },
      });
    },

    //
    handleMall(row) {
      // console.log('>>>', row);
      this.$router.push({
        path: '/basicdata/brand/basicdataTripartiteMall',
        query: {
          id: row.id,
          name: '商场 - ' + row.clientName,
        },
      });
    },
    //打开文件
    downloadLink(row) {
      window.open(
        'http://192.168.10.100:8012/onlinePreview?url=' +
          encodeURIComponent(Base64.encode(row.leaseAccessories))
      );
    },
    //控制控货
    makeCargo(row) {
      console.log('控货操作！！', row);
      let r = {
        id: row.id,
        cargoControl: row.cargoControl,
      };
      this.$confirm(`确定要修改${row.clientName}的控货状态吗？`, {
        type: 'warning',
        //beforeClose 阻止关闭弹窗
        beforeClose: async (action, instance, done) => {
          //下面这行代码就是弹出的确认删除和取消删除
          if (action === 'confirm') {
            // 调取接口
            updateCargoControl(r).then(res => {
              console.log(res);
              if (res.statusText == 'OK') {
                this.onLoad(this.page);
                this.$message({
                  type: 'success',
                  message: '操作成功!',
                });
                done();
              } else {
                this.$message({
                  type: 'warning',
                  message: '操作失败!',
                });
              }
            });
          } else {
            //点击其他地方时就相当于点击了false
            //done 关闭窗口
            this.data.map(item => {
              if (item.id == row.id) {
                item.cargoControl = !item.cargoControl;
              }
              return item;
            });
            done();
          }
        },
      });
    },
    uploadSuccess(fileList) {
      console.log('123123123', fileList);
      // this.form.fileName =
      // this.$set(row, 'imageCos', fileList);
      if (this.title == '编辑') {
        this.bianji = true;
      }
    },
    handleRemove(file) {
      console.log('3333333', file);
      let id1 = this.fileList.findIndex(item => {
        if (item.id == file.url) {
          return true;
        }
      });
      this.fileList.splice(id1, 1);
      console.log('fileList', this.fileList);
    },
    handleCo(file, fileList) {
      // console.log('3333333',file, fileList);
      this.showImgViewer = false;
    },
    //文件上传前的一些业务需要的校验
    beforeUploadFn(file, fileList) {
      // console.log("上传校验");
      let fileNameLength = file.name.lastIndexOf('.'); // 文件名开始到最后一个点的长度
      let fileFormat = file.name.substring(fileNameLength + 1, file.name.length);
      fileFormat = fileFormat.toLowerCase();
      let imgArr = ['txt'];
      if (imgArr.includes(fileFormat)) {
        // this.warning(this.$t('lang.fileFormat'))
        return false;
      } else {
        return true;
      }
    },
    handlePreview(file) {
      console.log('111111', file);
      this.imgPreviewUrl[0] = file.response.data.link;
      // this.imgPreviewUrl[0] = file.url;
      // this.imgPreviewUrl[0] = this.$api + file.response.data.id
      this.showImgViewer = true;

      console.log('-=-=sc上传', this.fileList);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    async init() {
      //客户字典
      getDictionaryBiz('client_type').then(res => {
        // console.log("字典》》》",res);
        this.clientType = res.data.data;
        this.$functions.checkcColumnList('clientTypeName', this.columnList).checkarr =
          res.data.data.map(item => {
            item.value = item.dictKey;
            item.label = item.dictValue;
            return item;
          });
      });
      //字典
      getDictionaryBiz('basic_freight_type').then(res => {
        // console.log("字典》》》",res);
        this.freightType = res.data.data;
      });
      //字典
      getDictionaryBiz('distribution_type').then(res => {
        // console.log("字典》》》",res);
        this.distributionType = res.data.data;
      });
      // console.log("globalc.optioner===",globalc.optioner);
      // let optioner = JSON.parse(localStorage.getItem('optioner'));
      // // console.log("-=-=-=-=",optioner);
      //  if(optioner.length > 0){
      //    this.optioner = optioner
      //    console.log("打印》》》",this.optioner);
      //  }else{
      //     globalc.useGetGlobalProperties().then(res =>{
      //       this.optioner = res;
      //       console.log("打印》》》",this.optioner);
      //       localStorage.setItem("optioner",JSON.stringify(globalc.optioner))
      //    });
      //  }

      // console.log('市111', this.optioner);
      this.height = this.setPx(document.body.clientHeight - 340);
      getLazyTreeAll().then(res => {
        if (res.data.success) {
          this.optioner = res.data.data;
          this.onLoad(this.page);
        }
      });
    },
    searchHide() {
      this.search = !this.search;
    },
    searchChange() {
      this.onLoad(this.page);
    },
    searchReset() {
      this.query = {};
      this.dataShi = '';
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    handleSubmit(from) {
      console.log('上传的集合。。', JSON.parse(JSON.stringify(this.fileList)));
      if (this.title == '编辑' && this.bianji == false) {
        console.log('编辑1111');
        if (this.fileList.length > 0) {
          let li = [];
          this.fileList.forEach(it => {
            li.push(it.url);
          });
          this.form.leaseAccessories = li.length > 0 ? li.join(',') : null;
        } else {
          // return this.$message.warning('请上传文件！');
        }
      } else {
        if (this.fileList.length > 0) {
          let li = [];
          this.fileList.forEach(it => {
            li.push(it.response.data.link);
            this.form.fileName = it.response.data.originalName;
          });
          this.form.leaseAccessories = li.length > 0 ? li.join(',') : null;
        } else {
          // return this.$message.warning('请上传文件！');
        }
      }

      if (!this.form.id) {
        console.log('添加提交的数据：', this.form);
        this.$refs[from].validate(valid => {
          if (valid) {
            // this.form.typeService = !!this.form.typeService ? parseInt(this.form.typeService) : undefined;
            this.form.bladeRegionCityId = this.form.bladeRegionProvinceId[1];
            this.form.bladeRegionAreaId = this.form.bladeRegionProvinceId[2];
            this.form.bladeRegionProvinceId = this.form.bladeRegionProvinceId[0];
            console.log('上传llll>>>', this.form);
            add(this.form).then(() => {
              this.box = false;
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '操作成功!',
              });
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      } else {
        this.$refs[from].validate(valid => {
          if (valid) {
            console.log('修改提交的数据：', this.form);
            // this.form.typeService = !!this.form.typeService ? parseInt(this.form.typeService) : undefined;
            this.form.bladeRegionCityId = this.form.bladeRegionProvinceId[1];
            this.form.bladeRegionAreaId = this.form.bladeRegionProvinceId[2];
            this.form.bladeRegionProvinceId = this.form.bladeRegionProvinceId[0];
            update(this.form).then(() => {
              this.box = false;
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '操作成功!',
              });
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }
    },
    handleAdd() {
      this.title = '新增';
      this.form = {};
      this.fileList = [];
      this.box = true;
      this.distriType = false;
      this.viewClientEntd = false;
    },
    handleAddSon(row) {
      console.log(row);
      this.$router.push({
        path: '/basicdata/brand/basicClientFrom',
        query: {
          id: row.id,
          name: '新增 - ' + row.clientName,
        },
      });
    },
    handleEdit(row) {
      this.title = '编辑';
      this.fileList = [];
      this.box = true;
      this.distriType = false;
      this.viewEntd = false;
      this.viewClientEntd = true;
      getDetail(row.id).then(res => {
        this.form = res.data.data;
        if (this.form.detailedly == '0' || this.form.detailedly == '-1') {
          this.form.detailedly = '';
        }
        let bus = [];
        this.form.typeServiceBusiness.forEach(i => {
          bus.push(i.typeService);
          if (i.typeService == '3') {
            this.distriType = true;
            this.form.businessType = i.mold;
          }
        });
        if (!!bus) {
          this.form.typeServiceList = bus;
        }

        let a = [];
        if (!!this.form.bladeRegionProvinceId) {
          if (res.data.data?.bladeRegionProvinceId) {
            a.push(res.data.data.bladeRegionProvinceId);
          }
          if (res.data.data?.bladeRegionCityId) {
            a.push(res.data.data.bladeRegionCityId);
          }
          if (res.data.data?.bladeRegionAreaId) {
            a.push(res.data.data.bladeRegionAreaId);
          }
        }
        this.form.bladeRegionProvinceId = a;
        if (!!this.form.leaseAccessories) {
          if (this.form.leaseAccessories.includes(',')) {
            let le = [];
            let d = this.form.leaseAccessories.splice(',');
            d.forEach(i => {
              let q = {
                name: '',
                url: i,
              };
              le.push(q);
            });
            this.fileList = le;
          } else {
            this.fileList = [
              {
                name: this.form.fileName,
                url: this.form.leaseAccessories,
              },
            ];
          }
        }
      });
    },
    handleView(row) {
      this.title = '查看';
      // this.view = true;
      // this.box = true;
      // this.fileList = [];
      this.$router.push({
        path: '/basicdata/brand/basicClientDetail',
        query: {
          id: row.id,
        },
      });
      return;
    },
    handleDrawer(row) {
      this.basicClientId = row.id;
      this.drawer = true;
    },
    handleBrand(row) {
      //品牌
      this.$router.push({
        path: '/basicdata/brand/basicdataStoreBrand',
        query: {
          id: row.id,
          name: '品牌 - ' + row.clientName,
        },
      });
    },

    //历史记录
    handleHistory(row) {
      // this.basicClientId = row.id;
      // this.drawer = true;
      // this.$router.push('/basicdata/brand/basicHistoricalContract?id='+row.id+";name="+row.clientName);

      this.$router.push({
        path: '/basicdata/brand/basicHistoricalContract',
        query: {
          id: row.id,
          name: '历史记录 - ' + row.clientName,
        },
      });
    },
    //仓库
    handleEntrepot(row) {
      // this.basicClientId = row.id;
      // this.drawer = true;
      // this.$router.push('/basicdata/brand/basicHistoricalContract?id='+row.id+";name="+row.clientName);

      this.$router.push({
        path: '/basicdata/brand/basicStorageServices',
        query: {
          id: row.id,
          name: '服务仓 - ' + row.clientName,
          type: '2',
        },
      });
    },
    //联系人
    handleLinkman(row) {
      this.$router.push({
        path: '/basicdata/brand/basicStoreContact',
        query: {
          id: row.id,
          name: '联系人 - ' + row.clientName,
        },
      });
    },
    //基地
    handleBase(row) {
      this.$router.push({
        path: '/basicdata/brand/basicdataCustomerBase',
        query: {
          id: row.id,
          name: '基地 - ' + row.clientName,
        },
      });
    },
    //商场
    handleStore(row) {
      this.$router.push({
        path: '/basicdata/brand/basicShop',
        query: {
          id: row.id,
          name: '门店- ' + row.clientName,
        },
      });
    },
    handleDrawerClose() {
      this.basicClientId = '';
      this.drawer = false;
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.selectionClear();
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    beforeClose(done) {
      done();
      this.form = {};
      this.view = false;
    },
    onClose(done) {
      console.log('执行了');
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      // this.$refs.table.clearSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      // console.log('-=-=', this.query);
      if (this.dataShi.length > 0) {
        // console.log('-=-=', this.dataShi);
        this.query.contractStartTime = this.dataShi[0];
        this.query.contractEntTime = this.dataShi[1];
      }
      if (!!this.query.bladeRegionProvinceId) {
        this.query.bladeRegionCityId = this.query.bladeRegionProvinceId[1];
        this.query.bladeRegionAreaId = this.query.bladeRegionProvinceId[2];
        this.query.bladeRegionProvinceId = this.query.bladeRegionProvinceId[0];
      }
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        console.log(data);

        data.records.forEach(i => {
          let ke = this.clientType.find(kh => parseInt(kh.dictKey) == parseInt(i.clientType));
          // console.log("客户类型<><><>",ke);
          if (!!ke) {
            i.clientTypeName = ke.dictValue;
            // console.log('==-=-=', i.clientType, ke.dictKey, ke.dictValue);
          }
          if (!i.clientType) {
            i.clientTypeName = '无';
          }
          let typeServiceName = [];

          if (!i.typeServiceBusiness) {
            i.typeServiceName = '无';
          } else {
            i.typeServiceBusiness.forEach(ty => {
              let fuw = this.freightType.find(
                fw => parseInt(fw.dictKey) == parseInt(ty.typeService)
              );
              if (!!fuw) {
                // console.log("fuw",fuw);
                typeServiceName.push(fuw.dictValue);
                // console.log('==-=-=', i.typeService, fuw.dictKey, fuw.dictValue);
              }
            });
            i.typeServiceName = typeServiceName.join(',');
          }
        });
        let dz = '';
        data.records.forEach(it => {
          let arrsheng = this.optioner.filter(i => {
            return it.bladeRegionProvinceId == i.value;
          });
          if (arrsheng.length == 0) return;
          // console.log("========",JSON.parse(JSON.stringify(arrsheng)) );
          let arrshi = arrsheng[0].children.filter(i => {
            return it.bladeRegionCityId == i.value;
          });
          // console.log("========",JSON.parse(JSON.stringify(arrsheng)) );
          let arrqu = arrshi[0].children.filter(i => {
            return it.bladeRegionAreaId == i.value;
          });
          // console.log("========",JSON.parse(JSON.stringify(arrsheng)) );
          dz =
            arrsheng[0].label +
            (arrshi[0].label ? `/${arrshi[0].label}` : ``) +
            (arrqu[0]?.label ? `/${arrqu[0]?.label}` : '');
          it.bladeRegionProvinceId = dz;
        });

        // console.log("dzdz",dz);
        this.page.total = data.total;
        this.data = data.records;
        this.data = this.$functions.newdatas(this.columnList, this.data);
        this.loading = false;
        this.selectionClear();
      });
    },
  },
};
</script>

<style scoped lang='scss'>
.el-form-item__content {
  height: 30px;
}
.el-times {
  :deep(.el-tooltip__trigger) {
    height: 32px !important;
  }
}
.fr-fo{
  width: 100%;
  display: flex;
    justify-content: space-between;
}
.el-btn{
  margin-right:0;
}
</style>
