<template>
  <div>
    <el-card shadow="hover" class="mgb20">
      <div class="flex-between">
        <div class="per_title" v-preventReClick @click="goback(0)">
          <i class="el-icon-arrow-left"></i>
          <span class="per_back">返回</span>
          <span v-if="form.customerName || !customerId" class="per_school"
            v-text="isDetail ? form.customerName + '/查看' : (customerId ? form.customerName + '/编辑' : '新增')"></span>
        </div>
      </div>
    </el-card>

    <el-card shadow="hover" class="card">
      <div class="tabs" v-if="customerId">
        <a class="item" v-for="(item, i) in tabs" :key="i" :class="{ active: i == curTab }" @click="tabChange(i)">{{
          item
        }}</a>
      </div>
      <div v-show="curTab === 'tab1'">
        <el-form :model="form" :rules="rules" ref="form" label-width="120px" class="flex-start-around info"
          :disabled="isDetail">
          <el-col :span="6" style="margin-right: 60px;">
            <el-form-item prop="countries" label="国家">
              <el-select v-model="form.countries" clearable placeholder="请选择国家">
                <el-option v-for="(item, index) in countryList" :key="index" :label="item.name"
                  :value="item.name"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="schoolId" label="客户名称">
              <div class="flex a-center">
                <el-select v-model="form.schoolId" filterable clearable placeholder="请选择学校" :disabled="!!customerId"
                  @change="SchoolChange" @clear="clearSchool">
                  <el-option v-for="(item, index) in schoolList" :key="index" :label="item.schoolName"
                    :value="item.schoolId"></el-option>
                </el-select>
                <!-- <i v-if="!isDetail"
                   class="el-icon-circle-plus-outline plus-cus"
                   @click="addCustomer"></i> -->
                <el-button v-if="!isDetail" style="margin-left: 5px" type="primary" size="mini"
                  @click="setCustomer">设置</el-button>
              </div>
            </el-form-item>
            <el-form-item prop="cityId" label="城市">
              <el-select v-model="form.cityId" placeholder="" disabled>
                <el-option v-for="(item, index) in cityList" :key="index" :label="item.cityName"
                  :value="item.cityId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="industryId" label="行业">
              <el-select v-model="form.industryId" clearable placeholder="请选择行业"
                :disabled="form.industryClassId ? false : true">
                <el-option v-for="(item, index) in industryList" :key="index" :label="item.industryName"
                  :value="item.industryId"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="account" label="账号">
              <el-input placeholder="请输入账号" v-model.trim="form.account"></el-input>
            </el-form-item>
            <el-form-item label="职务">
              <el-input placeholder="请输入职务名称" v-model.trim="form.position" maxlength="11"></el-input>
            </el-form-item>
            <el-form-item label="产品到期时间">
              <el-date-picker type="date" disabled v-model="form.expireDate" style="width: 100%;"
                value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="6" style="margin-left: 60px;">
            <el-form-item label="客户类型">
              <el-select v-model="form.customerType" placeholder="下单后客户类型自动补充" disabled>
                <el-option v-for="(item, index) in customerTypeList" :key="index" :label="item.name"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="provinceId" label="省份">
              <el-select v-model="form.provinceId" placeholder="" disabled>
                <el-option v-for="(item, index) in provinceList" :key="index" :label="item.provinceName"
                  :value="item.provinceId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="industryClassId" label="行业类型">
              <el-select v-model="form.industryClassId" clearable placeholder="请选择行业类型" @change="changIndustry"
                @clear="clearIndustry()">
                <el-option v-for="(item, index) in IndustryClassList" :key="index" :label="item.industryClassName"
                  :value="item.industryClassId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="name" label="联系人姓名">
              <el-input placeholder="请输入联系人姓名" v-model.trim="form.name"></el-input>
            </el-form-item>
            <el-form-item prop="phone" label="手机号">
              <el-input placeholder="请输入联系人手机号" v-model.trim="form.phone" maxlength="11"></el-input>
            </el-form-item>
            <el-form-item prop="email" label="邮箱">
              <el-input placeholder="请输入邮箱" v-model.trim="form.email"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
        <div v-if="!isDetail" style="margin-top: 20px;text-align: center">
          <el-button type="primary" v-preventReClick @click="saveAdd(0)">确定</el-button>
          <el-button v-preventReClick @click="$router.back()">取消</el-button>
        </div>
      </div>

      <div v-show="curTab === 'tab2'">
        <div class="tool">
          <ul class="filter">
            <li>
              <label>产品分类</label>
              <el-select v-model="form2.productType" placeholder="请选择产品类型" clearable @change="filterForm2">
                <el-option v-for="(item, index) in productTypeList" :key="index" :label="item.classificationName"
                  :value="item.classificationId"></el-option>
              </el-select>
            </li>
            <li>
              <label>订阅状态</label>
              <el-select v-model="form2.status" placeholder="请选择订阅状态" @change="filterForm2">
                <el-option v-for="(item, index) in subStatusList" :key="index" :label="item.name"
                  :value="item.name"></el-option>
              </el-select>
            </li>
            <li>
              <el-input style="width: 250px;" placeholder="请输入产品名称" prefix-icon="el-icon-search" clearable
                v-model="form2.keyword"></el-input>
            </li>
          </ul>
          <div>
            <el-button type="primary" @click="exportList">导出列表</el-button>
          </div>
        </div>
        <el-table :data="products" class="orderTable" header-align="center" @selection-change="handleSelectionChange"
          row-key="id">
          <el-table-column type="selection" width="55" align="center" :reserve-selection="true"></el-table-column>
          <el-table-column type="index" width="100" label="序号" align="center">
          </el-table-column>
          <el-table-column prop="goodsName" label="产品名称" align="center"></el-table-column>
          <el-table-column prop="productTypeName" label="产品分类" align="center"></el-table-column>
          <el-table-column label="起止日期" align="center">
            <template slot-scope="scope">
              {{ scope.row.status === '已过期' ? '-' : scope.row.startAndEndTime }}
              <el-tooltip v-if="scope.row.other" class="item" effect="dark" placement="top">
                <div slot="content">
                  还有<span v-html="scope.row.other"></span><br>的订单还未生效
                </div>
                <i class="el-icon-warning warning"></i>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="剩余期限" align="center">
            <template slot-scope="scope">
              {{ scope.row.remain }}&nbsp;&nbsp;天
            </template>
          </el-table-column>
          <el-table-column prop="status" label="订阅状态" align="center"></el-table-column>
          <el-table-column label="产品状态" align="center">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.isEnable" :active-value="1" :inactive-value="0"
                :active-text="scope.row.isEnable ? '启用' : '禁用'" :disabled="scope.row.status === '已过期'"
                @change="switchOff($event, scope.row, scope.$index)"></el-switch>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination background layout="total, prev, pager, next" @current-change="handleCurrentChangeProduct"
            :current-page="pageProduct" :page-size="pageSizeProduct" :total="totalProduct"></el-pagination>
        </div>
      </div>

      <div v-show="curTab === 'tab3'">
        <div class="tool">
          <ul class="filter">
            <li>
              <label>订单类型</label>
              <el-select v-model="form3.orderType" clearable placeholder="请选择订单类型" @change="initOrder">
                <el-option v-for="(item, index) in orderTypeList" :key="index" :label="item.name"
                  :value="item.value"></el-option>
              </el-select>
            </li>
            <li>
              <label>订单状态</label>
              <el-select v-model="form3.orderStatus" clearable placeholder="请选择订单状态" @change="initOrder">
                <el-option v-for="(item, index) in orderStatusList" :key="index" :label="item.name"
                  :value="item.id"></el-option>
              </el-select>
            </li>
          </ul>
          <div>
            <el-input style="width: 250px;" placeholder="请输入订单编号、内容" prefix-icon="el-icon-search" clearable
              v-model="form3.keyword"></el-input>
          </div>
        </div>
        <el-table :data="orders" class="orderTable" header-align="center" @selection-change="handleSelectionChange"
          row-key="orderId">
          <el-table-column type="selection" width="55" align="center" :reserve-selection="true"></el-table-column>
          <el-table-column type="index" width="100" label="序号" align="center">
          </el-table-column>
          <el-table-column prop="orderNumber" label="订单编号" align="center"></el-table-column>
          <el-table-column prop="orderContent" label="订单内容" align="center">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top" style='width: 500px'
                v-if='scope.row.orderContent && scope.row.orderContent.length > 14'>
                <p> {{ scope.row.orderContent }}</p>
                <div slot="reference" class="name-wrapper">
                  <el-tag size="medium" class='tags'>{{ scope.row.orderContent }}</el-tag>
                </div>
              </el-popover>
              <span v-else>
                {{ scope.row.orderContent }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="orderAmount" label="订单金额（元）" align="center"></el-table-column>
          <el-table-column prop="createTime" label="订单日期" align="center"></el-table-column>
          <el-table-column prop="orderType" label="订单类型" align="center"></el-table-column>
          <el-table-column prop="orderStatus" label="订单状态" align="center"></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="toOrderDetail(scope.row)">订单详情</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination background layout="total, prev, pager, next" @current-change="handleCurrentChangeOrder"
            :current-page="pageOrder" :page-size="pageSizeOrder" :total="totalOrder"></el-pagination>
        </div>
      </div>

      <div v-show="curTab === 'tab4'">
        <div class="tool">
          <div>
            <el-input style="width: 350px;" placeholder="请输入订单编号、合同名称、合同编号、产品内容" prefix-icon="el-icon-search"
              clearable></el-input>
          </div>
        </div>
        <el-table :data="contractInformations" class="table" header-align="center">
          <el-table-column type="index" width="100" label="序号" align="center">
          </el-table-column>
          <el-table-column prop="contractNumber" label="订单号" align="center"></el-table-column>
          <el-table-column prop="contractNumber" label="合同编号" align="center"></el-table-column>
          <el-table-column prop="contractName" label="合同名称" align="center">
          </el-table-column>
          <el-table-column prop="endTime" label="合同期限" align="center">
            <template slot-scope="scope">
              {{ scope.row.startTime ? scope.row.startTime.split('').shift() : ''
              }}&nbsp;&nbsp;&nbsp;-&nbsp;&nbsp;&nbsp;{{ scope.row.endTime ? scope.row.endTime.split('').shift() : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="dataOrCourseName" label="产品内容" align="center">
          </el-table-column>
          <el-table-column prop="contractMoney" label="合同金额" align="center">
            <template slot-scope="scope">
              {{ scope.row.contractMoney }}&nbsp;&nbsp;元
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="showContract(scope.row)">查看</el-button>
              <el-button type="text" @click="showContract(scope.row)">下载</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-show="curTab === 'tab5'">
        <div class="tool">
          <div>
            <el-input style="width: 300px;" placeholder="请输入商务经理、手机号" prefix-icon="el-icon-search" clearable
              v-model="bmsKeyword"></el-input>
          </div>
        </div>
        <el-table :data="bms" class="table" header-align="center">
          <el-table-column type="index" width="100" label="序号" align="center"></el-table-column>
          <el-table-column prop="userName" label="姓名" width="200" align="center">
            <template slot-scope="scope">
              {{ scope.row.userName }}{{ scope.row.peopleDel ? '(已被删除)' : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="手机号" width="150" align="center"></el-table-column>
          <el-table-column prop="bmName" label="所属团队" align="center">
            <template slot-scope="scope">
              <div v-html="scope.row.bmName"></div>
            </template>
          </el-table-column>
          <el-table-column prop="quantityOfOrder" label="订单数量" width="100" align="center"></el-table-column>
          <el-table-column prop="latestTime" label="最近下单时间" width="200" align="center"></el-table-column>
          <el-table-column prop="productName" label="产品" align="center" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" width="120" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="toOrder(scope.row)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination background layout="total, prev, pager, next" @current-change="handleCurrentChangeBm"
            :current-page="pageBm" :page-size="pageSizeBm" :total="totalBm"></el-pagination>
        </div>
      </div>
    </el-card>

    <el-dialog :visible.sync="showImg" width="70%" center>
      <img :src="fileSrc" width="100%" alt="">
    </el-dialog>

    <el-dialog :title="curRow ? '编辑客户' : '添加客户'" :visible.sync="customerVisible" width="300px" class="dialog"
      :close-on-click-modal="false">
      <el-form label-width="70px">
        <el-form-item label="客户名称">
          <el-input v-model="customerForm.schoolName" placeholder="请输入客户名称"></el-input>
        </el-form-item>
        <el-form-item prop="userName" label="省份">
          <el-select v-model="customerForm.provinceId" placeholder="请选择省份" @change="provinceChange">
            <el-option v-for="(item, index) in provinceList" :key="index" :label="item.provinceName"
              :value="item.provinceId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="userName" label="城市">
          <el-select v-model="customerForm.cityId" placeholder="请选择城市"
            :disabled="customerForm.provinceId ? false : true">
            <el-option v-for="(item, index) in cities" :key="index" :label="item.cityName"
              :value="item.cityId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="customerVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCustomer">确定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="客户字典设置" :visible.sync="customerListVisible" width="800px" class="dialog"
      :close-on-click-modal="false" custom-class="customer-dia">
      <div style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 10px">
        <el-input style="width: 200px;" placeholder="请输入客户名称" prefix-icon="el-icon-search" v-model="customerKeyword"
          clearable></el-input>
        <i class="el-icon-circle-plus plus-cus" @click="addCustomer"></i>
      </div>
      <el-table :data="customers" class="table" ref="table" header-align="center" row-key="customerId">
        <el-table-column type="index" width="100" label="序号" align="center">
          <template slot-scope="scope">
            {{ scope.$index + (pageCustomer - 1) * pageSizeCustomer + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="客户名称" align="center">
          <template slot-scope="scope">
            {{ scope.row.customerName || scope.row.schoolName }}
          </template>
        </el-table-column>
        <el-table-column prop="provinceName" label="省份" align="center">
        </el-table-column>
        <el-table-column prop="cityName" label="城市" align="center">
        </el-table-column>
        <el-table-column prop="countries" label="是否为客户" align="center">
          <template slot-scope="scope">
            {{ scope.row.bindOrNot ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="scope">
            <i class="el-icon-edit icon" @click="editCustomer(scope.row)"></i>
            <i v-if="!scope.row.bindOrNot" class="el-icon-delete icon" @click="delCustomer(scope.row, i)"></i>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background layout="total, prev, pager, next" :total="totalCustomer"
          @current-change="handleCurrentChangeCustomer" :current-page="pageCustomer" :page-size="pageSizeCustomer">
        </el-pagination>
      </div>
    </el-dialog>
    <pdf :visible.sync="pdfVisible" :src.sync="fileSrc"></pdf>
  </div>
</template>

<script>
import pdf from '../../components/pdf.vue'
import Util from '@/libs/util'
import axios from 'axios'
import qs from 'qs'
export default {
  components: { pdf },
  data () {
    return {
      token: sessionStorage.getItem('token'),
      customerId: this.$route.query.id,
      isDetail: Boolean(this.$route.query.show),
      curTab: this.$route.query.type || 'tab1',
      tabs: {
        tab1: '基本信息',
        tab2: '已订阅产品',
        tab3: '订单记录',
        tab4: '合同信息',
        tab5: '商务经理',
      },
      showFile: false,
      pdfVisible: false,
      showImg: false,
      fileSrc: '',
      form: {
        customerId: "",
        customerName: '',
        countries: '中国',
        industryClassId: 16,
        industryId: 83,
        provinceId: '',
        account: '',
        name: '',
        phone: '',
        position: '',
        cityId: '',
        customerType: '',
        expireDate: '',
        email: '',
        schoolId: ''
      },
      rules: {
        countries: [
          { required: true, message: '请输入国家', trigger: 'blur' }
        ],
        provinceId: [
          { required: true, message: '请输入省份', trigger: 'blur' }
        ],
        cityId: [
          { required: true, message: '请输入城市', trigger: 'blur' }
        ],
        // customerType: [
        //     { required: true, message: '请选择客户类型', trigger: 'change' }
        // ],
        name: [
          { required: true, message: '请输入联系人姓名', trigger: 'blur' }
        ],
        account: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          {
            pattern: /^[A-Za-z0-9]{4,}$/,
            message: "请输入正确的账号",
            trigger: "blur"
          }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        schoolId: [
          { required: true, message: '请选择客户名称', trigger: 'change' }
        ],
        email: [
          // { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            pattern: /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
            message: '请输入正确的邮箱',
            trigger: 'blur'
          }
        ],
        industryId: [
          { required: true, message: '请选择行业', trigger: 'change' }
        ],
        industryClassId: [
          { required: true, message: '请选择行业类型', trigger: 'change' }
        ],
      },
      customerTypeList: [{
        name: '正式',
        value: 1
      },
      {
        name: '试用',
        value: 2
      },
      {
        name: '到期',
        value: 3
      }],

      form2: {
        productType: '',
        status: '全部',
        keyword: ''
      },
      // 产品类型
      productTypeList: [
        {
          id: '',
          name: '全部'
        },
        {
          id: 1,
          name: '实训课程产品'
        },
        {
          id: 0,
          name: '理论课程产品'
        },
        {
          id: 3,
          name: '数据产品'
        },
        {
          id: 4,
          name: '职站增值模块'
        }
      ],
      // 订阅状态
      subStatusList: [
        {
          id: '',
          name: '全部'
        },
        {
          id: 1,
          name: '生效中'
        },
        {
          id: 2,
          name: '已过期'
        },
        {
          id: 3,
          name: '待生效'
        }
      ],
      products: [],
      productAll: [],
      productAllOrigin: [],
      pageProduct: this.$route.query.type === 'tab2' ? (+this.$route.query.page || 1) : 1,
      pageSizeProduct: 10,
      totalProduct: 0,

      form3: {
        orderType: +this.$route.query.orderType || '',
        orderStatus: +this.$route.query.orderStatus || '',
        keyword: this.$route.query.keyword || ''
      },
      // 订单类型
      orderTypeList: [{
        name: '全部',
        value: ''
      }, {
        name: '正式',
        value: 1
      }, {
        name: '试用',
        value: 2
      }],
      // 订单状态
      orderStatusList: [
        {
          id: '',
          name: '全部'
        },
        {
          id: 1,
          name: '已完成'
        },
        {
          id: 2,
          name: '待发货'
        }
      ],
      pageOrder: this.$route.query.type === 'tab3' ? (+this.$route.query.page || 1) : 1,
      pageSizeOrder: 10,
      totalOrder: 0,
      orders: [],

      bmsKeyword: '',
      bms: [],
      pageBm: this.$route.query.type === 'tab5' ? (+this.$route.query.page || 1) : 1,
      pageSizeBm: 10,
      totalBm: 0,

      countryList: [{
        name: '中国'
      }],
      provinceList: this.$store.state.provinceList,
      cityList: [],
      IndustryClassList: [],
      industryList: [],
      schoolList: [],
      contractInformations: [],
      coursePermissionss: [],
      dataPermissionss: [],
      multipleSelection: [],
      NoAdd: true,
      phoneRepeat: false,
      emailRepeat: false,
      submiting: false, // 新增编辑防抖标识
      updateTime: 0,
      customerVisible: false,
      cities: [],
      customerForm: {
        schoolName: '',
        provinceId: '',
        cityId: '',
      },

      customerListVisible: false,
      customers: [],
      pageCustomer: 1,
      pageSizeCustomer: 10,
      totalCustomer: 0,
      customerKeyword: '',
      curRow: null
    };
  },
  watch: {
    // 监听信息是否有更改,有的话页面离开的时候要询问是否要保存
    form: {
      handler () {
        this.updateTime++
      },
      deep: true
    },
    'form2.keyword': function (val) {
      clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.filterForm2()
      }, 500)
    },
    'form3.keyword': function (val) {
      this.pageOrder = 1
      clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.initOrder()
      }, 500)
    },
    bmsKeyword: function (val) {
      clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.getBm()
      }, 500)
    },
    customerKeyword: function (val) {
      clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.initCustomer()
      }, 500)
    },
  },
  mounted () {
    this.getIndustryClass()
    this.getBm()
    this.getCategory()
    if (this.customerId) {
      this.getProduct()
      this.$get(this.api.queryCustomerDetails, {
        customerId: this.customerId
      }).then((res) => {
        let customer = res.result.customer
        this.form = {
          customerId: customer.customerId,
          customerName: customer.customerName,
          schoolId: customer.schoolId,
          countries: customer.countries,
          industryClassId: customer.industryClassId,
          industryId: customer.industryId,
          provinceId: customer.provinceId,
          account: customer.account,
          phone: customer.phone,
          cityId: customer.cityId,
          customerType: customer.customerType,
          expireDate: customer.expireDate,
          email: customer.email,
          name: customer.name,
          position: customer.position,
        }
        this.getOrder()
        this.contractInformations = res.result.contractInformations.filter(e => e.contractNumber || e.contractName); // 必须有合同编号或者名称，否则不展示
        this.coursePermissionss = res.result.coursePermissionss
        this.dataPermissionss = res.result.dataPermissionss
        this.getCityData()
        this.changIndustryData()
        this.getSchool()
      }).catch((res) => { })
    } else {
      this.changIndustryData()
      this.getSchool()
    }
  },
  methods: {
    // 获取已订阅产品
    getProduct () {
      this.$get(this.api.getProductsSubscribedByCustomers, {
        customeId: this.customerId
      }).then(async ({ data }) => {
        data = data.filter(e => !e.productDel) // productDel=1的不显示
        const { productTypeList } = this
        const now = await Util.getNow()
        data.map((e, i) => {
          e.id = i
          const list = e.startAndEndTimeList
          if (list && list.length) {
            let connect = true // 每个订单的开始结束日期是否连续
            list.map((n, i) => {
              // 第一个不用计算。用当前订单的开始日期跟上一个订单的结束日期做比较，只差一天，就表示是连续订单
              if (i) {
                if (new Date(n.startTime).getTime() - 86400000 !== new Date(list[i - 1].endTime).getTime()) connect = false
              }
            })
            // 如果是连续订单，则取第一个订单的开始日期和最后一个订单的结束日期
            // if (list[0].startTime && list[0].endTime) {
            if (list[0].startTime && now < new Date(list[0].startTime)) {
              e.startTime = list[0].startTime
              e.endTime = connect ? list[list.length - 1].endTime : list[0].endTime
              e.status = '未生效'
              e.orderEnable = list[0].isEnable

              // 如果还有未生效的订单，页面上要显示出来
              if (!connect && list[1]) {
                const notActive = list.slice(1) // 取第一个订单以后的所有订单
                e.other = ''
                notActive.map(j => {
                  e.other += `<br>${j.startTime} ~ ${j.endTime}`
                })
              }
            } else if (list[list.length - 1].endTime && now > new Date(list[list.length - 1].endTime)) {
              e.status = '已过期'
            } else {
              // 连续订单
              if (connect) {
                e.startTime = list[0].startTime
                e.endTime = list[list.length - 1].endTime
                e.status = '生效中'
                e.orderEnable = list[0].isEnable
              } else {
                for (const j in list) {
                  const i = +j
                  const n = list[i]
                  if (n.startTime && n.endTime && now >= new Date(n.startTime) && now <= new Date(n.endTime)) {
                    // 生效中的订单，直接取该订单的开始结束日期
                    e.startTime = n.startTime
                    e.endTime = n.endTime
                    e.status = '生效中'
                    e.orderEnable = n.isEnable
                    // 如果还有未生效的订单，页面上要显示出来
                    if (list[i + 1]) {
                      const notActive = list.slice(i + 1) // 取当前订单以后的所有订单
                      e.other = ''
                      notActive.map(j => {
                        e.other += `<br>${j.startTime} ~ ${j.endTime}`
                      })
                    }
                    break
                  } else if (i != 0 && list[i - 1].endTime && n.startTime && n.endTime && now > new Date(list[i - 1].endTime) && now < new Date(n.startTime)) {
                    // 当前时间位于两个订单时间之间，则取次订单的开始结束日期，并且为未生效
                    e.startTime = n.startTime
                    e.endTime = n.endTime
                    e.status = '未生效'
                    e.orderEnable = n.isEnable
                    break
                  }
                }
              }
            }
            // }
            const date = new Date()
            date.setHours(0)
            date.setMinutes(0)
            date.setSeconds(0)
            e.remain = e.status === '已过期' ? 0 : this.getRemain(date.getTime(), e.endTime) // 获取剩余期限
            e.startAndEndTime = e.status === '已过期' ? '' : e.startTime + ' ~ ' + e.endTime
            const isHave = productTypeList.find(n => n.classificationId === e.productType)
            if (isHave) {
              e.productTypeName = isHave.classificationName
            } else {
              e.productTypeName = ''
            }
            // 1开启 0禁用（已过期的订单，或者当前生效的订单为禁用，则显示为禁用，否则是启用）
            e.isEnable = (e.status === '未生效' || e.status === '已过期' || !e.orderEnable) ?
              0 :
              1
          }
        })
        this.productAll = data
        this.productAllOrigin = data
        this.totalProduct = data.length
        this.handlePage()
      }).catch(res => { })
    },
    // 获取剩余日期
    getRemain (startTime, endTime) {
      return parseInt(((new Date(endTime) - new Date(startTime)) / 86400000))
    },
    // 分页
    handlePage () {
      this.products = this.productAll.slice((this.pageProduct - 1) * this.pageSizeProduct, this.pageProduct * this.pageSizeProduct)
    },
    handleCurrentChangeProduct (val) {
      this.pageProduct = val
      this.handlePage()
      this.$router.push(`addcustomer?id=${this.customerId}&type=tab2&page=${val}`)
    },
    // 已订阅产品筛选
    filterForm2 () {
      const list = this.productAllOrigin
      const { productType, status, keyword } = this.form2
      this.productAll = list.filter(e => (productType === '' || productType === e.productType) && (e.status === status || status === '全部') && (!e.goodsName || (e.goodsName && e.goodsName.includes(keyword))))
      this.pageProduct = 1
      this.totalProduct = this.productAll.length
      this.handlePage()
    },
    // 设置客户
    setCustomer () {
      this.initCustomer()
      this.customerListVisible = true
    },
    handleCurrentChangeCustomer (val) {
      this.pageCustomer = val
      this.getCustomer()
    },
    // 获取客户列表
    getCustomer () {
      this.$post(this.api.customerSettingsList, {
        pageNum: this.pageCustomer,
        pageSize: this.pageSizeCustomer,
        keyword: this.customerKeyword,
      }).then(({ page }) => {
        this.customers = page.records
        this.totalCustomer = page.total
      }).catch(res => { });
    },
    initCustomer () {
      this.pageCustomer = 1
      this.getCustomer()
    },
    // 创建客户
    addCustomer () {
      this.curRow = null
      this.customerForm = {
        schoolName: '',
        provinceId: '',
        cityId: '',
        customerId: '',
        schoolId: '',
      }
      this.customerVisible = true
    },
    // 编辑客户
    editCustomer (row) {
      this.curRow = row
      this.customerVisible = true
      this.customerForm = {
        schoolName: row.customerName || row.schoolName,
        provinceId: row.provinceId,
        cityId: row.cityId,
        customerId: row.customerId || '',
        schoolId: row.schoolId || '',
      }
      row.provinceId && this.provinceChange()
    },
    // 删除客户
    delCustomer (row, i) {
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      }).then(async () => {
        await this.$post(`${this.api.delClientsOrSchools}?schoolId=${row.schoolId}`).then(res => {
          this.$message.success('删除成功')
          this.getSchool(row.schoolId)
          this.getCustomer()
        })
      }).catch(() => { })
    },
    // 获取城市
    provinceChange (e) {
      this.$get(this.api.queryCity, {
        provinceId: this.customerForm.provinceId
      }).then(({ list }) => {
        this.cities = list
        if (e) this.customerForm.cityId = ''
      }).catch(res => { });
    },
    // 客户新增提交
    async submitCustomer () {
      if (this.submiting) return false
      const form = this.customerForm
      if (!form.schoolName) return this.$message.warning('请输入客户名称')
      if (!form.provinceId) return this.$message.warning('请选择省份')
      if (!form.cityId) return this.$message.warning('请选择城市')
      this.submiting = true

      const row = this.curRow
      form.customerName = form.schoolName
      let res
      try {
        if (this.curRow) {
          if (row.bindOrNot) {
            // 编辑客户
            res = await this.$post(this.api.clientSettingsEditClient, form)
          } else {
            // 编辑学校
            res = await this.$post(this.api.editClientsOrSchools, form)
          }
        } else {
          // 新增学校
          res = await this.$get(this.api.addNewCustomersByOneself, form)
        }
      } finally {
        this.submiting = false
      }

      this.customerVisible = false
      this.$message.success('添加成功')
      this.getCustomer()
      this.getSchool(!this.customerId ? res.schoolId || '' : '') // 新增才需要自动选中新加的客户
    },
    // 获取产品分类
    getCategory () {
      this.$get(this.api.productCategoryList).then(res => {
        this.productTypeList = res.classificationList
      }).catch(err => { })
    },
    // 已订阅产品导出
    exportList () {
      let list = this.productAll
      if (this.multipleSelection.length) list = this.multipleSelection
      const data = []
      list.map(e => {
        data.push({
          productName: e.productName,
          productStatus: e.status,
          productType: e.productTypeName,
          remainingPeriod: e.remain,
          startAndEndTime: e.startAndEndTime,
          subscriptionStatus: e.isEnable ? '启用' : '禁用',
        })
      })
      axios.post(this.api.exportSubscribedRecords, data, {
        headers: {
          token: this.token
        },
        responseType: 'blob'
      }).then((res) => {
        Util.downloadFileDirect(`已订阅产品.xls`, new Blob([res.data]))
      }).catch(res => { })
    },

    // 订单记录
    getOrder () {
      const { orderStatus, orderType, keyword } = this.form3
      this.$post(this.api.getCustomerOrderRecord, {
        customerId: this.customerId,
        cityId: '',
        orderContent: keyword,
        orderStatus,
        orderType,
        pageNo: this.pageOrder,
        pageSize: this.pageSizeOrder,
        provinceId: ''
      }).then(({ orders }) => {
        orders.records.forEach(e => {
          e.orderType = this.orderTypeFn(e.orderType)
          e.orderStatus = this.orderStatusFn(e.orderStatus)
        });
        this.orders = orders.records
        this.totalOrder = orders.total
      }).catch(res => { })
    },
    initOrder () {
      this.pageOrder = 1
      this.getOrder()
    },
    handleCurrentChangeOrder (val) {
      this.pageOrder = val
      this.getOrder()
      this.$router.push(`addcustomer?id=${this.customerId}&type=tab3&page=${val}`)
    },
    // 订单详情
    toOrderDetail (row) {
      this.$router.push(`/addcustomer?id=${this.customerId}&type=tab3&${qs.stringify(this.form3)}&page=${this.pageOrder}`)
      this.$router.push(`/AddOrder?val=watch&orderId=${row.orderId}&orderStatus=${row.orderStatus === '已完成' ? 1 : 0}`)
    },

    // 商务经理
    getBm () {
      this.$post(this.api.getAListOfClientBusinessManagers, {
        keywords: this.bmsKeyword,
        customerId: this.customerId,
        pageNum: this.pageBm,
        pageSize: this.pageSizeBm
      }).then(({ data }) => {
        data.records.map(e => {
          let name = ''
          // 拼接团队名称，teamDel：1已删除，0未删除
          e.teamInformationRespList.map(n => name += `${n.partnerClassificationName}${n.teamDel ? '（被解散）' : ''}<br>`)
          e.bmName = name
        })
        this.bms = data.records
        this.totalBm = data.total
      }).catch(res => { })
    },
    handleCurrentChangeBm (val) {
      this.pageBm = val
      this.getBm()
      this.$router.push(`addcustomer?id=${this.customerId}&type=tab5&page=${val}`)
    },
    // 商务经理查看
    toOrder (row) {
      this.$router.push(`/addcustomer?id=${this.customerId}&type=tab5&keyword=${this.bmsKeyword}&page=${this.pageOrder}`)
      this.$router.push(`/bmOrder?businessManagerId=${row.businessManagerId}&customerId=${this.customerId}&customerName=${this.form.customerName}&userName=${row.userName}&teamId=${row.teamId}`)
    },

    // tab切换
    tabChange (index, to) {
      // 当前tab是第一个，并且不是从确认询问后跳过来的，就直接调询问框询问是否保存
      if (this.curTab === 'tab1' && !to) {
        this.goback(index)
      } else {
        this.curTab = index
        this.$router.push(`addcustomer?id=${this.customerId}&type=${index}`)
        this.pageProduct = 1
        this.pageOrder = 1
        this.pageBm = 1
        index === 'tab3' && this.initOrder()
        this.updateTime = this.form.customerId ? 1 : 0
      }
    },
    // 获取城市
    getCityData () {
      this.$get(this.api.queryCity, {
        provinceId: this.form.provinceId
      }).then(res => {
        this.cityList = res.list
      }).catch(res => { });
    },
    // 清除学校
    clearSchool () {
      this.form.provinceId = '',
        this.form.cityId = '',
        this.form.customerName = ''
    },
    // 获取学校/客户名称
    getSchool (schoolId) {
      this.$get(this.api.querySchoolData).then(({ list }) => {
        this.schoolList = list
        // 有传schoolId，则需要找到这个学校然后赋值表单
        if (schoolId && !this.customerId) {
          const item = list.find(e => e.schoolId == schoolId)
          if (item) {
            this.form.schoolId = schoolId
            this.form.provinceId = item.provinceId
            this.getCityData()
            this.form.cityId = item.cityId
          } else {
            this.form.schoolId = ''
          }
        }
      }).catch(res => { });
    },
    // 查询客户是否存在
    SchoolChange (val) {
      this.clearSchool()
      if (val) {
        let obj = {}
        obj = this.schoolList.find((item) => {
          return item.schoolId === val
        });
        this.form.customerName = obj.schoolName
        this.form.provinceId = obj.provinceId
        this.getCityData()
        this.form.cityId = obj.cityId

        this.$get(this.api.queryCustomerIsExists, {
          schoolId: this.form.schoolId
        }).then(res => {
          this.NoAdd = true
        }).catch(res => {
          this.NoAdd = false
        })
      }
    },
    // 获取行业类
    getIndustryClass () {
      this.$get(this.api.queryCustomerIndustryClass).then(res => {
        this.IndustryClassList = res.list
      }).catch(res => { });
    },
    // 清除行业类
    clearIndustry () {
      this.form.industryId = ''
    },
    // 获取行业
    changIndustry () {
      this.clearIndustry()
      this.changIndustryData()
    },
    changIndustryData () {
      let data = {
        industryClassId: this.form.industryClassId
      }
      this.$get(this.api.queryCustomerIndustry, data).then(res => {
        this.industryList = res.list
      }).catch(res => { });
    },
    switchOff (val, row) {
      this.$post(`${this.api.orderBulkDisableEnable}?isOpen=${val}`, row.startAndEndTimeList.map(e => e.id)).then(res => {
        this.$message.success(val ? '启用成功' : '禁用成功')
      }).catch(res => { })
    },
    phoneChange () { // 切换手机号
      let regex = /^1[3456789]\d{9}$/;
      if (regex.test(this.form.phone)) {
        let url = "";
        if (!this.form.customerId) {
          url = `${this.api.checkEmailOrPhone}?phone=${this.form.phone}&email=`;
        } else {
          url = `${this.api.checkEmailOrPhone}?customerId=${this.form.customerId}&phone=${this.form.phone}&email=`;
        }
        this.$post(url).then(res => {
          if (res.status === 200) {
            this.phoneRepeat = false;
          }
        }).catch(err => {
          this.phoneRepeat = true;
        });
      }
    },
    emailChange () { // 切换邮箱
      let regex = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
      if (regex.test(this.form.email)) {
        let url = "";
        if (!this.form.customerId) {
          url = `${this.api.checkEmailOrPhone}?email=${this.form.email}&phone=`;
        } else {
          url = `${this.api.checkEmailOrPhone}?customerId=${this.form.customerId}&email=${this.form.email}&phone=`;
        }
        this.$post(url).then(res => {
          if (res.status === 200) {
            this.emailRepeat = false;
          }
        }).catch(err => {
          this.emailRepeat = true;
        });
      }
    },
    saveAdd (tab) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.submiting) return false
          if (this.phoneRepeat) {
            this.$message.warning("该手机号已存在");
            return;
          }
          if (this.emailRepeat) {
            this.$message.warning("该邮箱已存在");
            return;
          }
          this.submiting = true
          if (this.NoAdd) {
            let obj = {};
            obj = this.schoolList.find((item) => {
              return item.schoolId == this.form.schoolId;
            });
            this.form.customerName = obj.schoolName
            this.form.provinceId = obj.provinceId
            this.getCityData()
            this.form.cityId = obj.cityId
            let data = {
              customerName: this.form.customerName,
              customerId: this.customerId,
              schoolId: this.form.schoolId,
              countries: this.form.countries,
              industryClassId: this.form.industryClassId,
              industryId: this.form.industryId,
              provinceId: this.form.provinceId,
              account: this.form.account,
              phone: this.form.phone,
              cityId: this.form.cityId,
              customerType: this.form.customerType,
              expireDate: this.form.expireDate,
              email: this.form.email,
              name: this.form.name,
              position: this.form.position
            }
            if (this.customerId) {
              this.$post(this.api.updateCustomer, data).then((res) => {
                setTimeout(() => {
                  this.submiting = false
                }, 1500)
                this.$message.success('编辑成功')
                tab ? this.tabChange(tab, 1) : this.backPage()
              }).catch((res) => {
                this.submiting = false
              })
            } else {
              this.$post(this.api.addCustomer, data).then((res) => {
                setTimeout(() => {
                  this.submiting = false
                }, 1500)
                this.$store.commit('schoolIdData', { schoolId: this.form.schoolId })
                this.$message.success('添加成功')
                tab ? this.tabChange(tab, 1) : this.$router.push('/customer')
              }).catch((res) => {
                this.submiting = false
              })
            }
          } else {
            this.submiting = false
            this.$message.warning('该客户已存在')
          }
        }
      })
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    showContract (row) {
      if (!row.contractFile) return this.$message.warning('文件链接无效')
      let type = row.contractFile.split('.').pop()
      let img = ['jpg', 'gif', 'png', 'jepg']

      this.fileSrc = row.contractFile
      if (img.includes(type)) {
        this.showImg = true
      } else if ('pdf'.includes(type)) {
        this.pdfVisible = true
      } else {
        window.open(`https://view.officeapps.live.com/op/view.aspx?src=${this.fileSrc}`)
      }
    },
    goback (i) {
      const id = this.form.customerId
      const updateTime = this.updateTime
      // 更改了信息才需要提示
      if ((id && updateTime > 1) || (!id && updateTime)) {
        this.$confirm(`编辑的内容未保存，是否保存？`, '提示', {
          type: 'warning',
          closeOnClickModal: false
        }).then(() => {
          this.saveAdd(i)
        }).catch(() => {
          i ? this.tabChange(i, 1) : this.backPage()
        })
      } else {
        i ? this.tabChange(i, 1) : this.backPage()
      }
    },
    backPage () {
      this.$router.push(this.$store.state.referrer || '/customer')
    }
  }
};
</script>

<style lang="scss" scoped>
.tabs {
  margin-bottom: 30px;
}

.card {
  min-height: calc(100vh - 260px);
  margin-bottom: 20px;
}

.addhr_tag {
  background-color: #666;
  width: 6px;
  height: 17px;
  margin-right: 5px;
}

.radio_icon {
  font-size: 26px;
  color: #062c87;
}

/deep/.warning {
  margin-left: 5px;
  color: #062c87;
}

.tags {
  border: none;
  background: none;
  color: #000;
  white-space: pre-wrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
}

.info {
  margin-top: 20px;

  .el-select {
    width: 100%;
  }
}

.plus-cus {
  margin-left: 10px;
  font-size: 18px;
  color: #062c87;
  cursor: pointer;
}

/deep/.customer-dia {
  .icon {
    margin-right: 10px;
    font-size: 16px;
    color: #7a7a7a;
    cursor: pointer;

    &:hover {
      color: #062c87;
    }
  }
}
</style>
