<template>
    <div v-loading="loading">
        <!-- 订单详情 -->
        <div v-show="!showSelectClient">
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-card shadow="hover" class="mgb20">
                        <div class="flex-between">
                            <div class="per_title" v-preventReClick @click="goback()">
                                <i class="el-icon-arrow-left"></i>
                                <span class="per_back">返回</span>
                                <span class="per_school">订单处理</span>
                            </div>
                            <!-- 新增 -->
                            <el-button v-if="!disabled&&!editDisabled" type="primary" size="small" round class="mag"
                                       v-preventReClick @click="addOrder">确定
                            </el-button>
                            <!-- 修改 -->
                            <el-button v-if="editDisabled" type="primary" size="small" round class="mag"
                                       v-preventReClick @click="orderUpdate">确定
                            </el-button>
                        </div>
                    </el-card>

                    <el-card shadow="hover" class="mgb20">
                        <div>
                            <div class="flex-center mgb20 user_header">
                                <p class="addhr_tag"></p>
                                <span>基本信息</span>
                            </div>
                            <div>
                                <el-form ref="form" :model="form" :rules="rules" label-width="120px">
                                    <el-col :span="6" :offset="5">
                                        <el-form-item label="订单编号">
                                            <el-input v-model="form.orderNumber" disabled placeholder="自动生成"></el-input>
                                        </el-form-item>
                                        <el-form-item label="订单时间" prop="createTime">
                                            <el-date-picker
                                                disabled
                                                style="width:100%"
                                                v-model="form.createTime"
                                                type="date"
                                                placeholder="自动生成">
                                            </el-date-picker>
                                        </el-form-item>
                                        <el-form-item label="省份">
                                            <el-select disabled v-model="form.provinceId" clearable placeholder="请选择省份"
                                                       @change="getCity" @clear="clearprovince()">
                                                <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 label="联系人">
                                            <el-input disabled v-model="form.orderContact"
                                                      placeholder="请输入联系人姓名"></el-input>
                                        </el-form-item>
                                        <el-form-item label="邮箱">
                                            <el-input disabled v-model="form.email" placeholder="请输入邮箱地址"></el-input>
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="6" :offset="2">
                                        <el-form-item prop="customerName" label="订单客户">
                                            <div v-if="!disabled&&!editDisabled&&!renewDisabled" @click="gotoClient"
                                                 style="cursor: pointer">
                                                <el-input v-model="form.customerName" placeholder="请选择客户"></el-input>
                                            </div>
                                            <el-input v-if="disabled||editDisabled||renewDisabled" disabled
                                                      v-model="form.customerName" placeholder="请选择客户"></el-input>
                                        </el-form-item>
                                        <el-form-item prop="orderType" label="订单类型">
                                            <el-select :disabled="disabled||editDisabled||renewDisabled"
                                                       v-model="form.orderType" clearable placeholder="请选择订单类型">
                                                <el-option v-for="(item,index) in orderTypeList" :key="index"
                                                           :label="item.name" :value="item.value"></el-option>
                                            </el-select>
                                        </el-form-item>
                                        <el-form-item label="城市">
                                            <el-select disabled v-model="form.cityId" placeholder="请选择">
                                                <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 label="电话">
                                            <el-input disabled v-model="form.phone" placeholder="请输入电话号码"
                                                      maxlength="11"></el-input>
                                        </el-form-item>
                                        <el-form-item label="订单金额(元)" prop="orderAmount">
                                            <el-input disabled
                                                      oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                                                      type="number" v-model="form.orderAmount"
                                                      placeholder="请输入订单金额"></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-form>
                            </div>
                        </div>
                    </el-card>
                    <!-- 课程 -->
                    <el-card shadow="hover" class="mgb20">
                        <div>
                            <div class="flex-between mgb20 user_header">
                                <div class="flex-center">
                                    <p class="addhr_tag"></p>
                                    <span>课程权限</span>
                                </div>
                                <el-button v-if="!disabled&&!editDisabled" type="primary" size="small" round class="mag"
                                           @click="addClassJurisdiction()">添加
                                </el-button>
                            </div>

                            <el-table :data="jurisdictionData" class="orderTable" stripe header-align="center">
                                <el-table-column type="index" width="100" label="序号" align="center">
                                </el-table-column>
                                <el-table-column prop="productName" label="课程名称" align="center">
                                </el-table-column>
                                <el-table-column label="使用期限" align="center" width="200">
                                    <template slot-scope="scope">
                                        <div class="course-input">
                                            <el-input @change="deadLine($event,scope.row)" maxlength="4"
                                                      oninput="value=value.replace(/[^0-9.]/g,'')"
                                                      v-model="scope.row.periodOfUse" placeholder="输入时间"></el-input>
                                            <span>月</span>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="起止日期" align="center" width="200">
                                    <template slot-scope="scope">
                                        <p v-if="!scope.row.startDate">请输入使用期限，且确认发货</p>
                                        <div v-else style="display:flex;justify-content:center;">
                                            <p>{{ scope.row.startTime }}</p><span>&nbsp;&nbsp;-&nbsp;&nbsp;</span>
                                            <p>{{ scope.row.endTime }}</p>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="剩余期限" align="center">
                                    <template slot-scope="scope">
                                        <div class="small">
                                            <el-input v-model="scope.row.remainingPeriod" placeholder="请输入"
                                                      type="text"></el-input>
                                            <span>天</span>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="市场价" align="center">
                                    <template slot-scope="scope">
                                        <div class="small">
                                            <el-input v-model="scope.row.marketValue" placeholder="请输入"
                                                      type="text"></el-input>
                                            <span>万</span>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="成交价 " align="center">
                                    <template slot-scope="scope">
                                        <div class="small">
                                            <el-input @change="calculateDiscount($event,scope.row)"
                                                      v-model="scope.row.finalPrice" placeholder="请输入"
                                                      type="text"></el-input>
                                            <span>万</span>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="折扣率 " align="center">
                                    <template slot-scope="scope">
                                        <div class="small">
                                            <el-input v-model="scope.row.discountRate" placeholder="请输入"
                                                      type="text"></el-input>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="端口地址 " align="center">
                                    <template slot-scope="scope">
                                        <el-button @click="configure(scope.row)">配置</el-button>
                                    </template>
                                </el-table-column>
                                <el-table-column label="发货" align="center">
                                    <template slot-scope="scope">
                                        <el-switch
                                            :disabled="scope.row.ship ? true : false"
                                            v-model="scope.row.ship"
                                            :active-value="1"
                                            :inactive-value="0"
                                            @change="formSwitch($event,scope.row)">
                                        </el-switch>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-card>

                    <!-- 数据平台权限 -->
                    <el-card shadow="hover" class="mgb20">
                        <div>
                            <div class="flex-between mgb20 user_header">
                                <div class="flex-center">
                                    <p class="addhr_tag"></p>
                                    <span>数据平台权限</span>
                                </div>
                                <el-button v-if="!disabled&&!editDisabled&&!renewDisabled" type="primary" size="small"
                                           round class="mag" @click="addDataJurisdiction()">添加
                                </el-button>
                            </div>

                            <el-table :data="dataPlatform" class="orderTable" stripe header-align="center"
                                      :summary-method="getSummaries">
                                <el-table-column type="index" width="100" label="序号" align="center">
                                </el-table-column>
                                <el-table-column prop="productName" label="产品名称" align="center" width="200">
                                </el-table-column>
                                <el-table-column label="使用期限" align="center" width="200">
                                    <template slot-scope="scope">
                                        <div class="course-input">
                                            <el-input onkeyup="value=this.value.replace(/\D+/g,'')"
                                                      :class="!scope.row.periodOfUse&&whetherSubmit?'red':''"
                                                      :disabled="disabled||editDisabled" maxlength="4"
                                                      @change="deadLine($event,scope.row),zero($event,scope.row)"
                                                      oninput="value=value.replace(/[^0-9.]/g,'')"
                                                      v-model="scope.row.periodOfUse" placeholder="输入时间"></el-input>
                                            <span>月</span>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="起止日期" align="center" width="200">
                                    <template slot-scope="scope">
                                        <p v-if="!scope.row.startTime">请输入使用期限</p>
                                        <div v-else style="display:flex;justify-content:center;">
                                            <p>{{ scope.row.startTime }}</p><span>&nbsp;&nbsp;-&nbsp;&nbsp;</span>
                                            <p>{{ scope.row.endTime }}</p>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="剩余期限" align="center" width="200">
                                    <template slot-scope="scope">
                                        <div class="small">
                                            <el-input disabled v-model="scope.row.remainingPeriod" placeholder="请输入"
                                                      type="text"></el-input>
                                            <span style="margin-left:5px">天</span>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="市场价" align="center" width="200">
                                    <template slot-scope="scope">
                                        <div class="small">
                                            <el-input disabled v-model="scope.row.marketValue" placeholder="请输入"
                                                      type="text"></el-input>
                                            <span style="margin-left:5px">元&nbsp;/&nbsp;账号</span>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="成交价" align="center" width="200">
                                    <template slot-scope="scope">
                                        <div class="small">
                                            <el-input :class="!scope.row.finalPrice&&whetherSubmit?'red':''"
                                                      :disabled="disabled||editDisabled"
                                                      oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                                                      @change="[dealComputers($event,scope.row),calculateDiscount($event,scope.row),userAmount($event,scope.row)]"
                                                      v-model="scope.row.finalPrice" placeholder="请输入"
                                                      type="text"></el-input>
                                            <span style="margin-left:5px">元&nbsp;/&nbsp; 账号</span>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="折扣率" align="center" width="200">
                                    <template slot-scope="scope">
                                        <!-- <div class="discountRate"> -->
                                        <div class="small">
                                            <el-input disabled v-model="scope.row.discountRate" placeholder=""
                                                      type="text"></el-input>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column label="账号数" align="center" width="200">
                                    <template slot-scope="scope">
                                        <div class="small">
                                            <el-input :class="!scope.row.accountNum&&whetherSubmit?'red':''"
                                                      :disabled="disabled||editDisabled"
                                                      @change="[dealComputers($event,scope.row),dealBargain($event,scope.row),calculateDiscount($event,scope.row)]"
                                                      v-model="scope.row.accountNum" placeholder="请输入"
                                                      type="text"></el-input>
                                        </div>
                                    </template>
                                </el-table-column>
                                <!-- 金额自动计算，计算方式：账号数*成交价，且可以手动修改，保留两位小数 -->
                                <el-table-column label="总金额(元)" align="center" width="200">
                                    <template slot-scope="scope">
                                        <div class="small">
                                            <el-input :class="!scope.row.totalAmount&&whetherSubmit?'red':''"
                                                      :disabled="disabled||editDisabled"
                                                      @blur="[allAmount($event,scope.row),allAmountChange($event,scope.row),calculateDiscount($event,scope.row)]"
                                                      oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                                                      v-model="scope.row.totalAmount" placeholder="请输入"
                                                      type="text"></el-input>
                                        </div>
                                    </template>
                                </el-table-column>
                                <!-- <el-table-column label="端口地址 " align="center">
                                    <template slot-scope="scope">
                                        <el-button :disabled="disabled" @click="configure(scope.row)">配置</el-button>
                                    </template>
                                </el-table-column> -->
                                <el-table-column label="操作" align="center" width="230px">
                                    <template slot-scope="scope">
                                        <div class="flex-c-c">
                                            <el-button v-if="!editDisabled&&!disabled" style="margin-right:10px;"
                                                       @click="delDataForm(scope.$index)">删除
                                            </el-button>
                                            <!-- <el-button :disabled="disabled" v-show="scope.row.ship===true" style="margin-right:10px;" @click="configure(scope.row)">启动</el-button> -->
                                            <el-switch
                                                style="margin-right:10px"
                                                v-show="scope.row.ship"
                                                :disabled="disabled"
                                                v-model="scope.row.isEnable"
                                                :active-value="false"
                                                :inactive-value="true"
                                                active-text="启用"
                                                inactive-text="禁用"
                                                @change="formSwitch($event,scope.row)">
                                            </el-switch>
                                            <el-switch
                                                v-show="!scope.row.ship"
                                                :disabled="scope.row.ship||disabled"
                                                v-model="scope.row.ship"
                                                :active-value="true"
                                                :inactive-value="false"
                                                active-text="发货"
                                                inactive-text="未发货"
                                                @change="deliverGoods($event,scope.row)">
                                            </el-switch>
                                        </div>
                                    </template>
                                </el-table-column>
                                <!-- <el-table-column label="发货状态" align="center">
                                    <template slot-scope="scope">
                                    </template>
                                </el-table-column> -->

                            </el-table>
                        </div>
                    </el-card>
                    <!-- 合同 -->
                    <el-card shadow="hover" class="mgb20">
                        <div>
                            <div class="flex-center mgb20 user_header">
                                <p class="addhr_tag"></p>
                                <span>合同信息</span>
                            </div>
                            <div>
                                <el-form :disabled="disabled" ref="contract" :model="contract" :rules="rules"
                                         label-width="80px">
                                    <el-col :span="8" :offset="4">
                                        <el-form-item label="合同名称">
                                            <el-input v-model="contract.contractName" placeholder="请输入合同名称"></el-input>
                                        </el-form-item>

                                        <el-form-item label="合同金额" prop="contractInformationSum">
                                            <el-input oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                                                      v-model="contract.contractMoney" placeholder="请输入合同金额"></el-input>
                                        </el-form-item>
                                    </el-col>


                                    <el-col :span="8" :offset="2">
                                        <el-form-item label="合同编号">
                                            <el-input v-model="contract.contractNumber"
                                                      placeholder="请输入合同编号"></el-input>
                                        </el-form-item>
                                        <el-form-item label="合同期限">
                                            <div class="contractDate">
                                                <el-date-picker
                                                    v-model="contractTime"
                                                    style="wifth:100%"
                                                    type="daterange"
                                                    value-format="yyyy-MM-dd"
                                                    @change="contractTimeChange"
                                                    range-separator="至"
                                                    start-placeholder="开始日期"
                                                    end-placeholder="结束日期">
                                                </el-date-picker>
                                            </div>
                                        </el-form-item>

                                    </el-col>
                                    <el-col :span="24" :offset="4" class="flex-start">
                                        <el-form-item label="上传合同">
                                            <el-upload
                                                class="contract"
                                                :headers="{token}"
                                                :on-remove="handleRemove"
                                                :on-error="uploadError"
                                                :on-success="uploadSuccess"
                                                :before-upload="beforeAvatarUpload"
                                                :before-remove="beforeRemove"
                                                :limit="1"
                                                :on-exceed="handleExceed"
                                                :action="api.fileupload"
                                                :file-list="uploadList"
                                            >
                                                <el-button size="medium" type="plain" class="uploadTitle">上传</el-button>
                                            </el-upload>
                                        </el-form-item>
                                        <!-- <el-form-item>
                                            <el-button size="medium" type="plain" style="height:40px">重新上传</el-button>
                                        </el-form-item>                   -->
                                    </el-col>
                                </el-form>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>

            <!-- 添加课程权限弹框-->
            <el-dialog :visible.sync="classVisible" width="50%" center>
                <div class="flex-between mgb20">
                    <div class="flex-center">
                        <p class="addhr_tag"></p>
                        <span>课程列表</span>
                    </div>
                    <div>
                        <el-input placeholder="请输入课程名称" prefix-icon="el-icon-search" v-model.trim="curriculumName"
                                  @keyup.enter.native="addClassJurisdiction('search')" clearable></el-input>
                    </div>
                </div>
                <el-table v-loading="dataLoading" :data="permissionData" stripe header-align="center"
                          @selection-change="handleSelectionChange" row-key="cid">
                    <el-table-column type="selection" width="55" align="center"></el-table-column>
                    <el-table-column type="index" width="100" label="序号" align="center">
                    </el-table-column>
                    <el-table-column prop="curriculumName" label="课程名称" align="center">
                    </el-table-column>
                    <el-table-column prop="curriculumType" label="课程类型" align="center">
                    </el-table-column>
                    <el-table-column label="配置的实训应用" align="center">
                        <template slot-scope="scope">
                            <span class="ellipsis">{{ scope.row.sysName }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="expectedCourse" label="预计课时" align="center">
                    </el-table-column>
                </el-table>
                <div class="pagination">
                    <el-pagination background layout="total, prev, pager, next" :total="totals"
                                   @current-change="handleCurrentChange" :current-page="pageNo">
                    </el-pagination>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="classVisible = false">取 消</el-button>
                    <el-button type="primary" v-preventReClick @click="addSystem()">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 添加数据平台权限弹框 -->
            <el-dialog :visible.sync="showPlatform" width="50%" center>
                <div class="flex-between mgb20">
                    <div class="flex-center">
                        <p class="addhr_tag"></p>
                        <span>数据产品列表</span>
                    </div>
                    <div>
                        <el-input placeholder="请输入产品名称" prefix-icon="el-icon-search" v-model="productName"
                                  @keyup.enter.native="addDataJurisdiction('search')" clearable></el-input>
                    </div>
                </div>
                <el-table v-loading="dataLoading" :data="boxDataPlatform" stripe header-align="center"
                          @selection-change="boxDataPlatformSelection" row-key="id">
                    <el-table-column type="selection" :selectable="selectable" width="55"
                                     align="center"></el-table-column>
                    <el-table-column type="index" width="100" label="序号" align="center"></el-table-column>
                    <el-table-column prop="productName" label="产品名称" align="center"></el-table-column>
                    <el-table-column prop="tableNum" label="数据量（表）" align="center"></el-table-column>
                    <el-table-column prop="userName" label="创建人" align="center"></el-table-column>
                    <el-table-column prop="orderNum" label="订单数量" align="center"></el-table-column>
                    <el-table-column prop="market" label="市场价" align="center"></el-table-column>
                    <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
                    <!-- <el-table-column prop="orderNature" label="状态" align="center">
                        <template slot-scope="scope">
                            <p>{{scope.row.status ? '上架' : '下架'}}</p>
                        </template>
                    </el-table-column> -->
                </el-table>
                <div class="pagination">
                    <el-pagination background layout="total, prev, pager, next" :total="platfromTotals"
                                   @current-change="platfromCurrentChange" :current-page="platfromPage">
                    </el-pagination>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="showPlatform = false">取 消</el-button>
                    <el-button type="primary" v-preventReClick @click="addPlatform()">确 定</el-button>
                </span>
            </el-dialog>

            <!-- 选择IP -->
            <el-dialog :visible.sync="ipVisible" width="70%" center>
                <div class="flex-center mgb20">
                    <p class="hr_tag"></p>
                    <span>客户列表</span>
                </div>
                <el-table :data="IPData" stripe header-align="center">
                    <el-table-column type="index" width="100" label="序号" align="center">
                    </el-table-column>
                    <el-table-column prop="age" label="服务器名称" align="center">
                    </el-table-column>
                    <el-table-column label="IP" align="center">
                        <template slot-scope="scope">
                            <div class="tab_temp">
                                <div class="flex-center">
                                    <label>内网:</label>
                                    <el-input v-model="scope.row.Intranet" placeholder="请输入IP地址"></el-input>
                                </div>
                                <div class="flex-center mar10">
                                    <label>外网:</label>
                                    <el-input v-model="scope.row.extranet" placeholder="请输入端口号"></el-input>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="端口" align="center">
                        <template slot-scope="scope">
                            <div class="tab_temp">
                                <div class="flex-center">
                                    <label>内网:</label>
                                    <el-input v-model="scope.row.Intranet" placeholder="请输入内网IP地址"></el-input>
                                </div>
                                <div class="flex-center mar10">
                                    <label>外网:</label>
                                    <el-input v-model="scope.row.extranet" placeholder="请输入外网IP地址"></el-input>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="选择" align="center">
                        <template slot-scope="scope">
                            <i class="el-icon-success radio_icon"></i>
                        </template>
                    </el-table-column>
                </el-table>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="ipVisible = false">取 消</el-button>
                    <el-button type="primary" @click="IPSure()">确 定</el-button>
                </span>
            </el-dialog>
        </div>
        <!-- 选择客户 -->
        <select-client @back="backToOrder" v-show="showSelectClient" :refresh="showSelectClient"></select-client>
    </div>
</template>

<script>
import selectClient from "./selectClient.vue";

export default {
    components: {
        selectClient
    },
    data() {
        return {
            loading: false,// 页面加载
            disabled: false,// 查看禁用。
            editDisabled: false,// 编辑禁用
            renewDisabled: false,// 续费禁用
            dataLoading: false,// 产品弹框加载

            whetherSubmit: false,/* 提交否 */

            showSelectClient: false,// 切换展示选择客户页
            form: {// 基本信息
                // orderNumber: '',// 编号
                provinceId: "",// 省份id
                orderContact: "",// 联系人
                email: "",
                customerId: "",// 客户id
                orderType: "",
                cityId: "",
                phone: "",
                orderAmount: 0,
                // orderId: this.$store.state.orderId,
                customerName: ""// 客户名称
            },
            jurisdictionData: [{}],// 课程权限
            dataPlatform: [{}],// 数据平台data

            contract: { // 合同信息
                contractName: "",   // 合同名称
                contractFile: "",  // 合同文件
                contractMoney: "", // 合同金额
                contractNumber: "",// 合同编号
                startTime: "",     // 期限-头
                endTime: ""       // 期限-尾
                // orderId: '',       // 绑定订单id
            },
            contractTime: [],// 合同起止日期绑定值

            token: "",


            orderOther: {// 订单其他数据

            },
            uploadList: [],
            rules: {
                orderNumber: [
                    { required: true, message: "请输入订单编号", trigger: "blur" }
                ],
                customerName: [
                    { required: true, message: "请选择订单客户", trigger: "change" }
                ],
                orderContact: [
                    { required: true, message: "请输入联系人姓名", trigger: "blur" }
                ],

                orderType: [
                    { required: true, message: "请选择订单类型", trigger: "change" }
                ],
                phone: [
                    { required: true, message: "请输入手机号", trigger: "blur" },
                    {
                        pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
                        message: "请输入正确的手机号",
                        trigger: "blur"
                    }
                ],
                email: [
                    { required: true, message: "请输入邮箱地址", trigger: "blur" },
                    {
                        pattern: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
                        message: "请输入正确的邮箱",
                        trigger: "blur"
                    }
                ],

                orderAmount: [
                    // { pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/, message: '请输入正确金额格式,可保留两位小数' }
                    { required: true, message: "请输入订单金额", trigger: "blur" }

                    // { pattern: /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0)$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/, message: '请输入正确金额格式,可保留两位小数', trigger: 'blur'}
                ]
            },
            orderTypeList: [{
                name: "正式",
                value: 1
            },
                {
                    name: "试用",
                    value: 2
                }],
            provinceList: this.$store.state.provinceList,
            cityList: [],
            schoolList: [],


            yearList: [
                { name: "1个月", value: 30 },
                { name: "2个月", value: 60 },
                { name: "3个月", value: 90 },
                { name: "1年", value: 365 },
                { name: "2年", value: 730 },
                { name: "3年", value: 1095 }
            ],

            // 课程权限弹框
            classVisible: false,
            totals: 0,
            pageNo: 1,
            permissionData: [],
            multipleSelection: [],
            curriculumName: "",


            ipVisible: false,
            IPData: [
                {
                    id: 1,
                    age: "小额贷系统",
                    storeName: "1个月",
                    total: "2019.01.02 11:00",
                    payamount: "2019.01.02 11:00",
                    swtich: true,
                    Intranet: "10.20.202.1",
                    extranet: "10.20.202.1"
                },
                {
                    id: 2,
                    age: "小额贷系统",
                    storeName: "1个月",
                    total: "2019.01.02 11:00",
                    payamount: "2019.01.02 11:00",
                    swtich: true,
                    Intranet: "",
                    extranet: ""
                }
            ],
            curArr: "",
            test: [],

            // 数据平台权限弹框
            showPlatform: false,// 弹框显示
            platfromTotals: 0,// 列表条目
            platfromPage: 1,// 页码
            boxDataPlatform: [],// 数据平台弹框
            platformSelect: [],// 数据平台弹框选中
            productName: ""// 搜索产品名称


        };
    },
    async created() {
        this.token = sessionStorage.getItem("token");
        // 处于查看状态
        if (this.$route.query.watch) {
            this.disabled = true;
            await this.getDetail(this.$route.query.watch);
        }
        // 处于编辑状态
        if (this.$route.query.edit) {
            this.editDisabled = true;
            await this.getDetail(this.$route.query.edit);
        }
        /* 处于续费状态 */
        if (this.$route.query.renew) {
            this.renewDisabled = true;
            await this.getDetail(this.$route.query.renew);
        }
        this.getCityData();// 取得城市
    },

    methods: {
        // 读取页面详情
        async getDetail(id) {
            return this.$get(this.api.orderDetail, { orderId: +id }).then(res => {
                let form = res.orderDetails.order,// 基本信息
                    contract = res.orderDetails.contractInformation ? res.orderDetails.contractInformation : {},// 合同
                    list = res.orderDetails.orderOther;// 俩列表
                list.map(e => {
                    e.ship === 1 ? e.ship = true : e.ship = false;
                    e.isEnable ? e.isEnable = false : e.isEnable = true;
                });
                let dataArr = list.filter(e => {// 数据平台
                        if (this.renewDisabled) {/* 处于续费 */
                            let end = Date.parse(e.endTime);
                            let now = +new Date();
                            if (now < end) {
                                let time = e.endTime.split(" ")[0];
                                let arr = time.split("-");
                                e.startTime = arr[0] + "-" + arr[1] + "-" + "0" + (+arr[2] + 1);
                            } else {/* 过期 */
                                e.startTime = "";
                            }
                            e.endTime = "";
                            e.periodOfUse = "";
                        } else {
                            e.startTime = e.startTime.split(" ")[0];
                            e.endTime = e.endTime.split(" ")[0];
                        }
                        return e.authority === 0;
                    }),
                    classArr = list.filter(e => {// 课程权限
                        return e.authority === 1;
                    });
                this.form = {
                    orderNumber: form.orderNumber,
                    createTime: form.createTime,
                    provinceId: form.provinceId,
                    orderContact: form.orderContact,
                    email: form.email,
                    customerId: form.customerId,
                    customerName: form.customerName,
                    orderType: form.orderType,
                    cityId: form.cityId,
                    phone: form.phone,
                    orderAmount: form.orderAmount,
                    orderId: form.orderId
                };
                this.contract = {
                    contractName: contract.contractName,
                    contractMoney: contract.contractMoney,
                    contractNumber: contract.contractNumber,
                    startTime: contract.startTime ? contract.startTime : "",
                    endTime: contract.endTime ? contract.endTime : "",
                    contractId: contract.contractId,
                    uploadList: {
                        name: contract.contractFile ? contract.contractFile.split("/").pop() : "",
                        url: contract.contractFile
                    }
                };
                if (contract.startTime && contract.endTime) {
                    this.contractTime = [contract.startTime, contract.endTime];
                }
                this.dataPlatform = dataArr;
            });
        },
        // 新增订单
        addOrder() {
            if (this.dataPlatform.length === 0) {
                return this.$message.error("请选择产品后再确认订单！");
            }
            let verify =
                this.dataPlatform.some(e => {
                    if (!e.periodOfUse || !e.finalPrice || !e.accountNum || !e.totalAmount) {
                        return false;
                    } else {
                        return true;
                    }
                });
            if (!verify) {
                this.whetherSubmit = true;
                setTimeout(() => {
                    this.whetherSubmit = false;
                }, 4000);
                return this.$message.error("请把产品参数输入完整！");
            }
            if (this.dataPlatform) {

            }
            this.dataPlatform.map(e => {
                e.ship ? e.ship = 1 : e.ship = 0;
                e.isEnable ? e.isEnable = 0 : e.isEnable = 1;
            });
            this.jurisdictionData.map(e => {
                e.ship ? e.ship = 1 : e.ship = 0;
                e.isEnable ? e.isEnable = 0 : e.isEnable = 1;
            });
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    let renew = this.dataPlatform.some(e => e.renew);
                    if (this.renewDisabled || renew) {/* 续费状态下 */
                        this.form.orderNature = 2;
                        if (renew) {
                            this.dataPlatform.forEach(e => {
                                if (e.renew) delete e.renew;
                            });
                        }
                    }
                    let param = {
                        contractInformation: this.contract,//合同信息
                        order: this.form,// 订单基本数据
                        orderOther: [...this.dataPlatform, ...this.jurisdictionData]//订单其他数据
                    };
                    this.loading = true;
                    this.$post(this.api.orderAdd, param).then(res => {
                        this.$router.push("/order");
                        this.loading = false;
                        this.$message.success("添加订单成功！");
                    }).catch(err => {
                        this.loading = false;
                    });
                } else {
                    this.$message("请填上必填项!");
                    return false;
                }
            });

        },
        // 编辑订单确定
        orderUpdate() {
            this.dataPlatform.map(e => {
                e.ship ? e.ship = 1 : e.ship = 0;
                e.isEnable ? e.isEnable = 0 : e.isEnable = 1;
            });
            this.jurisdictionData.map(e => {
                e.ship ? e.ship = 1 : e.ship = 0;
                e.isEnable ? e.isEnable = 0 : e.isEnable = 1;
            });
            let param = {
                contractInformation: this.contract,//合同信息
                order: this.form,// 订单基本数据
                orderOther: [...this.dataPlatform, ...this.jurisdictionData]//订单其他数据
            };
            this.loading = true;
            this.$post(this.api.orderUpdate, param).then(res => {
                this.$message.success("修改成功！");
                this.loading = false;
                this.$router.push("/order");
            }).catch(err => {
                this.loading = false;

            });
        },
        /* 处理0开头的期限 */
        zero(e, row) {
            if (e[0] == "0") {
                row.periodOfUse = e.substring(1);
                this.zero(row.periodOfUse, row);
            }
        },
        // 订单客户框触发选择页面
        gotoClient() {
            this.showSelectClient = !this.showSelectClient;
        },
        // 选择客户返回传值
        backToOrder(val) {
            this.showSelectClient = !this.showSelectClient;
            if (val.id) {
                this.form.customerName = val.name;
                this.form.customerId = val.id;
                this.form.phone = val.phone;
                this.form.email = val.email;
                this.form.orderContact = val.name;
                this.$get(this.api.queryCustomerDetails, { customerId: val.id }).then(res => {
                    this.form.provinceId = res.result.customer.provinceId;
                    this.form.cityId = res.result.customer.cityId;
                    this.getCityData();
                });
                this.$forceUpdate();
            }
        },
        // 课程列表数据
        addClassJurisdiction(val) {
            if (val !== "search") {
                this.classVisible = !this.classVisible;
            }
            let param = {
                pageSize: 10,
                pageNum: this.platfromPage,
                curriculumName: this.curriculumName
            };
            this.dataLoading = true;
            this.$post(this.api.curriculumList, param).then(res => {
                this.permissionData = res.page.records;
                this.platfromTotals = res.page.total;
                this.dataLoading = false;
            }).catch(err => {
                this.dataLoading = false;
            });
        },
        // 课程--弹框列表选中
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        // 课程弹框--页数变更
        handleCurrentChange(val) {
            this.pageNo = val;
            this.addClassJurisdiction();
        },
        async addSystem() {
            if (!this.form.customerId) return this.$message.warning("请先选择客户！");
            if (this.multipleSelection.length > 0) {

            } else {
                return this.$message.warning("请选择课程");
            }
        },
        // 数据平台列表数据
        addDataJurisdiction(val) {
            if (val !== "search") {
                this.showPlatform = !this.showPlatform;
            }
            let param = {
                pageSize: 10,
                pageNum: this.platfromPage,
                status: 1,
                productName: this.productName
            };
            this.dataLoading = true;
            this.$post(this.api.listByEntity, param).then(res => {
                this.boxDataPlatform = res.pageList.records;
                this.platfromTotals = res.pageList.total;
                this.dataLoading = false;
            }).catch(err => {
                this.dataLoading = false;
            });
        },
        // 数据平台--弹框列表选中
        boxDataPlatformSelection(val) {
            this.platformSelect = val;
        },
        // 数据平台弹框--确定
        async addPlatform() {
            if (!this.form.customerId) return this.$message.warning("请先选择客户！");
            if (this.platformSelect.length > 0) {
                let that = this;
                let fn = function(e) {
                    let obj = {
                        productName: e.productName,// 名称
                        periodOfUse: "",// 使用期限
                        dataOrCourseId: e.id,// id
                        accountNum: "",// 账号数
                        startTime: "",// 开始
                        endTime: "", // 终止
                        remainingPeriod: "",// 剩余期限
                        marketValue: e.market,// 市场价
                        finalPrice: "",// 成交价
                        discountRate: "",// 折扣率
                        totalAmount: "",// 总价
                        ship: false,// 发货否
                        authority: 0// 数据平台权限
                    };
                    that.dataPlatform.push(obj);
                };
                let idArr = [];
                this.platformSelect.map(e => {// 取得选中的值，进行赋值
                    idArr.push(e.id);
                    if (this.dataPlatform.length > 0) {
                        // 比对是否存在该id，若存在，不操作，不存在，则进行push操作
                        let find = this.dataPlatform.some(i => e.id === i.dataOrCourseId);// 判断已有的相同的id不进行处理
                        if (!find) {
                            fn(e);
                        }
                    } else {
                        fn(e);
                    }
                });
                this.showPlatform = !this.showPlatform;
                this.platformSelect = [];

                /* 调接口，判断是否为客户已有的产品功能 */
                let params = {
                    authority: 0,
                    customerId: this.form.customerId,
                    productId: idArr
                };
                await this.$post(this.api.renew, params).then(res => {
                    this.dataPlatform.map(e => {
                        res.orderOthers.map(el => {
                            if (el.dataOrCourseId === e.dataOrCourseId) {
                                let time = el.endTime.split(" ")[0];
                                let arr = time.split("-");
                                e.startTime = arr[0] + "-" + arr[1] + "-" + "0" + (+arr[2] + 1);
                                e.endTime = "";
                                e.periodOfUse = "";
                                e.renew = true;
                            }
                        });
                    });
                });

            } else {
                return this.$message.warning("请选择数据");
            }
        },
        // 数据平台弹框--页数变更
        platfromCurrentChange(val) {
            this.platfromPage = val;
            this.addDataJurisdiction();
        },
        // 计算折扣率
        calculateDiscount(val, row) {
            if (row.finalPrice)
                row.discountRate = (row.finalPrice / row.marketValue * 100).toFixed(2) + "%";
        },
        // 已知成交和总额，计算账号数目
        userAmount(val, row) {
            if (val && row.totalAmount) {
                row.accountNum = Math.floor(row.totalAmount / val);
            }
        },
        //  合同起止日期选择
        contractTimeChange(val) {
            if (val.length > 0) {
                this.contract.startTime = val[0];
                this.contract.endTime = val[1];
            }
        },
        // 新增数据平台权限时，计算总的金额数目
        allAmount($event, row) {
            // 课程权限未完善，没写
            let arr = [];
            this.dataPlatform.map(e => {
                arr.push(+e.totalAmount);
            });
            this.form.orderAmount = arr.reduce((a, b) => a + b);
        },
        // 总金额触发--计算账号或市场价
        allAmountChange(val, row) {
            if (row.totalAmount) {
                let all = row.totalAmount;
                if (row.accountNum) {// 若有账号
                    row.finalPrice = Math.round(all / row.accountNum).toFixed(2);
                }
                if (row.finalPrice) {// 若有市场价
                    row.accountNum = Math.floor(all / row.finalPrice);
                }
            }
        },
        // 计算成交总额
        dealComputers(e, row) {
            if (row.finalPrice && row.accountNum) {
                row.totalAmount = Math.round((row.finalPrice) * (row.accountNum)).toFixed(2);
            }
            this.allAmount();
        },
        // 计算成交价
        dealBargain(e, row) {
            if (row.accountNum && row.totalAmount) {
                row.finalPrice = Math.round(row.totalAmount / row.accountNum).toFixed(2);
            }
        },
        // 权限switch切换--计算天数
        formSwitch(e, row) {
        },
        // 数据平台--发货
        deliverGoods(e, row) {
            if (this.editDisabled) {
                this.$post(this.api.ship + "?id=" + `${row.dataOrCourseId}`).then(res => {
                });
                // this.$post(this.api.ship,{id:4}).then(res=>{
            }
        },
        // 使用期限转换以及计算剩余天数
        deadLine(e, row) {
            function completeDate(value) {
                if (value == 0) return "12";
                return value < 10 ? "0" + value : value;
            }

            let char = "-";
            let nowDate = new Date();
            let day = nowDate.getDate();
            let month = nowDate.getMonth() + 1;
            let year = nowDate.getFullYear();

            if (this.renewDisabled || row.renew) {/* 处于续费状态 */
                if (!e) return row.endTime = "";
                let arr = row.startTime.split("-");
                let renewY = arr.shift();/* 年 */
                let renewM = arr.shift();/* 月 */
                let renewD = arr.shift();/* 日 */
                let endYear = +renewY + (parseInt((+renewM + (+e)) / 13) === 0 ? 0 : parseInt((+renewM + (+e)) / 12)) + char + completeDate((+renewM + (+e)) % 12) + char + renewD;
                row.endTime = endYear;

                // 计算剩余天数
                let date1 = Date.parse(endYear);
                let date2 = Date.parse(row.startTime);
                let ms = Math.abs(date1 - date2);
                row.remainingPeriod = Math.floor(ms / (24 * 3600 * 1000));

            } else {
                if (e === "") {
                    row.startTime = "";
                    row.endTime = "";
                    return;
                }
                //补全0，并拼接当前的时间点
                let nowYear = year + char + completeDate(month) + char + completeDate(day);
                // 判断结束日期
                let endYear = year + (parseInt((+month + (+e)) / 12) === 0 ? 0 : parseInt((+month + (+e)) / 12)) + char + completeDate((+month + (+e)) % 12) + char + completeDate(day);
                // 得出起始年月日
                row.startTime = nowYear;
                row.endTime = endYear;
                // 计算剩余天数
                let date1 = Date.parse(endYear);
                let date2 = Date.parse(nowYear);
                let ms = Math.abs(date1 - date2);
                let days = Math.floor(ms / (24 * 3600 * 1000));
                row.remainingPeriod = days;
            }


        },
        // 删除数据平台产品
        delDataForm(index) {
            this.$confirm("确定要删除吗？", "提示", {
                type: "warning"
            }).then(() => {
                if (this.renewDisabled && this.dataPlatform.length === 1) {
                    return this.$message.warning("续费至少保留一条产品信息！");
                } else {
                    this.dataPlatform.splice(index, 1);
                }
            });
        },
        // 清除省份
        clearprovince() {
            this.form.cityId = "",
                this.form.customerId = "",
                this.form.orderContact = "";
            this.form.phone = "";
            this.form.email = "";
        },
        // 获取城市
        getCity() {
            this.clearprovince();
            this.getCityData();
        },
        getCityData() {
            let data = {
                provinceId: this.form.provinceId
            };
            return this.$get(this.api.queryCity, data).then(res => {
                this.cityList = res.list;
            }).catch(res => {
            });
        },
        // 清除城市
        clearcity() {
            this.form.customerId = "",
                this.form.orderContact = "";
            this.form.phone = "";
            this.form.email = "";
        },
        // 获取学校/客户名称
        getSchool() {
            this.clearcity();
            this.getSchoolData();
        },
        getSchoolData() {
            let data = {
                provinceId: this.form.provinceId,
                cityId: this.form.cityId
            };
            this.$get(this.api.queryOrderCustomer, data).then(res => {
                this.schoolList = res.message;
            }).catch(res => {
            });
        },
        clearcustomer() {
            this.form.orderContact = "";
            this.form.phone = "";
            this.form.email = "";
        },
        // 获取学校/客户信息
        getcustomer() {
            let data = {
                customerId: this.form.customerId
            };
            this.$get(this.api.queryOrderCustomerContact, data).then(res => {
                this.form.orderContact = res.message[0].adminName;
                this.form.phone = res.message[0].adminPhone;
                this.form.email = res.message[0].email;
            }).catch(res => {
            });
        },

        // // 获取应用配置
        // getConfig(rows){
        //     this.multipleSelection = []
        //     let data = {
        //         courseId: this.curArr,
        //         searchContent: this.configSearch,
        //         pageNo: this.pageNo,
        //         pageSize: this.pageSize,
        //     }
        //     this.$get(this.api.queryCourseList,data).then(res => {
        //         res.message.rows.forEach(e => {
        //             e.courseType = this.courseTypeStatus(e.courseType)
        //             e.courseHours = this.hoursStatus(e.courseHours)
        //         })
        //         this.permissionData = res.message.rows
        //         this.totals = res.message.total
        //         this.classVisible = true
        //     }).catch(res => {});
        // },
        // onSearch(){
        //     this.getConfig()
        // },
        getRowKeys(row) {
            return row.courseId;
        },

        // // 绑定实训配置
        // addSystem() {
        //     this.classVisible = false     
        //     let arr = this.multipleSelection
        //     let result = arr.map(e => e.courseId).join()
        //     this.curArr = this.curArr.concat(`,${result}`)
        //     if (this.curArr.substr(0,1)==','){
        //         this.curArr = this.curArr.substr(1);
        //     }
        //     let data = {
        //         courseId: result,
        //     }
        //     this.getPermissions(data)
        // },


        // 查询应用权限
        getPermissions(val) {
            this.$get(this.api.queryCoursePermissions, val).then(res => {
                this.classVisible = false;
                var arritem = {
                    usePeriod: 30,
                    transactionPrice: "",
                    discount: "",
                    isDeliverGoods: 0,
                    portAddressId: 1,
                    orderId: this.form.orderId
                };
                let arryNew = [];
                res.message.map(item => {
                    arryNew.push(Object.assign({}, item, arritem));
                });
                this.jurisdictionData = this.jurisdictionData.concat(arryNew);
            }).catch(res => {
            });
        },
        deljur(index, row) {
            this.$confirm("确定要删除该课程吗？", "提示", {
                type: "warning"
            })
                .then(() => {
                    let newArr = this.curArr.split(",");
                    this.removeByValue(newArr, row.courseId);
                    var newStr = newArr.toString();
                    this.curArr = newStr;
                    this.jurisdictionData.splice(index, 1);
                    this.$message.success("删除成功");
                })
                .catch(() => {
                });
        },
        // discountChange(row){
        //     let reg = /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/
        //     if(!(reg.test(row.transactionPrice))){
        //         this.$message.error('请输入正确金额格式,可保留两位小数！');
        //         row.transactionPrice = ''
        //     }else{
        //         row.discount = this.Percentage(row.transactionPrice,row.marketPrice)
        //     }
        // },
        getSummaries(param) {
            const { columns, data } = param;
            var sums = 0;
            data.map(e => {
                sums += Number(e.transactionPrice);
            });
            this.form.orderAmount = sums;
            return sums;
        },

        // 上传文件超出
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 1 个文件，如需更换，请删除上一个文件再重新选择！`
            );
        },
        // 上传前
        beforeAvatarUpload(file) {
            const size = file.size / 1024 / 1024 < 10;
            let type = file.name.split(".").pop();
            let str = ["jpg", "jepg", "gif", "png", "doc", "docx", "pdf"].includes(type.toLowerCase());
            if (!str) {
                this.$message.error("只能上传图片，word文件和pdf文件！");
            } else if (!size) {
                this.$message.error("上传头像图片大小不能超过 10MB!");
            }
            return str && size;

        },
        // 上传成功
        uploadSuccess(response, file, fileList) {
            this.contract.contractFile = response.filesResult.fileUrl;
        },
        // 上传报错
        uploadError(err, file, fileList) {
            this.$message({
                message: "上传出错，请重试！",
                type: "error",
                center: true
            });
        },
        // 删除上传文件前的确认
        beforeRemove(file, fileList) {
            let type = file.name.split(".").pop();
            let str = ["jpg", "jepg", "gif", "png", "doc", "pdf"].includes(type.toLowerCase());
            const size = file.size / 1024 / 1024 < 10;
            if (!size || !str) {
                return true;
            } else {
                return this.$confirm(`确定移除 ${file.name}？`);
            }
        },
        // 删除文件钩子
        handleRemove(file, fileList) {
            this.contract.contractFile = "";
        },

        configure() {
            this.ipVisible = true;
        },
        IPSure() {
            this.ipVisible = false;
        },
        goback() {
            this.$router.go(-1);
        },
        /* 表格禁用 */
        selectable(row, index) {
            let boolean = true;
            this.dataPlatform.length && this.dataPlatform.some(e => {
                if (e.dataOrCourseId === row.id) {
                    boolean = false;
                }
            });
            return boolean;
        }

    }
};
</script>

<style lang="scss" scoped>
/deep/ .course-input .el-input__inner {
    width: 100px;

}

/deep/ .course-input .red .el-input__inner {
    border: 1px solid red;
}

/deep/ .small .red .el-input__inner {
    border: 1px solid red;
}

/deep/ .small .el-input__inner {
    width: 100%;
    margin-right: 5px;
}

/deep/ .discountRate .el-input__inner {
    width: 85px;
}

/deep/ .contractDate .el-date-editor--daterange.el-input__inner {
    width: 100%;
}

.mag {
    margin-right: 20px;
}

.uploadTitle {
    width: 100%;
    height: 40px;
    font-size: 16px;
}

.application_input {
    width: 250px;
}

.contract .el-upload {
    width: 100% !important;
}

.downcol .el-form-item__content {
    margin-left: 0 !important;
}

.down {
    // margin-top: 60px;
    height: 40px;
}

/* 选择IP */
.tab_temp label {
    width: 60px;
}

.mar10 {
    margin-top: 10px;
}

.radio_icon {
    font-size: 26px;
    color: #9278FF;
}

.ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
</style>
