<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-form class="queryFormInline" :model="queryParams" ref="queryForm" :inline="true">
          <el-row :span="24" type="flex" justify="space-between" align="middle">
            <el-col :span="22">
              <el-form-item label="品牌名称">
                <el-input
                  v-model="queryParams.brand_name"
                  placeholder="请输品牌名称"
                  clearable
                  size="small"
                />
              </el-form-item>

              <el-form-item label="品牌经营类型：">
                <el-select v-model="queryParams.brand_type" clearable size="small" placeholder="全部品牌类型">
                  <el-option
                    v-for="item in brandTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="品牌状态：">
                <el-select v-model="queryParams.status" clearable size="small" placeholder="全部状态">
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查 询</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-form-item style="float: right">
                <el-button type="primary" size="mini" icon="el-icon-plus" @click="addBrand">新 增</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-table :data="brandList" :height="tableHeight">
        <el-table-column label="品牌名称" prop="brand_cn" align="center"></el-table-column>
        <el-table-column label="品牌经营类型" prop="brand_type" align="center">
          <template slot-scope="scope">
            {{ scope.row.brand_type === 1 ? '自有品牌' : '品牌厂商授权' }}
          </template>
        </el-table-column>
        <el-table-column label="品牌商标注册号" prop="brand_number" align="center"></el-table-column>
        <el-table-column label="品牌状态" prop="status" align="center">
          <template slot-scope="scope">
            {{ brandStatusFormatter(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="授权期限" align="center">
          <template slot-scope="scope">
            <span>{{ timeFormatter(scope.row.brand_start_time) }}</span>
            <span>--</span>
            <span>{{ timeFormatter(scope.row.brand_end_time) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核说明" prop="last_check_content" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="editBrand(scope.row)" :disabled="(scope.row.id === 1)">编辑</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="text" size="small" @click="deleteBrand(scope.row)" :disabled="(scope.row.id === 1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.limit"
        @pagination="getList"
      ></pagination>
    </el-card>
    <!-- 新增/修改/详情 -->
    <el-dialog :title="brandTitle" :visible.sync="isOpen" width="70%" class="brandInf-add" center
               :close-on-click-modal="false" :before-close="handleCancel">
      <el-form :model="brandForm" :rules="brandRules" ref="brandForm" label-width="140px">
        <el-row v-if="indexBrandId != 0 && brandForm.status != 3">
          <p class="brand-status-con">
            <span v-if="brandForm.status == 1" class="color-spe-success"><i class="el-icon-success"></i></span>
            <span v-if="brandForm.status == 2" class="color-spe-error"><i class="el-icon-error"></i></span>
            <span v-if="brandForm.status == 0" class="color-spe-waiting"><i class="el-icon-success"></i></span>
            <span class="brand-form-status-text">{{ statusVal }}</span>
            <span v-if="brandForm.status == 2"><span class="brand-refused-title">原因：</span>{{ brandForm.last_check_content }}</span>
          </p>
        </el-row>
        <p class="brand-title-tips">请您严格按照商标注册证书信息填写，否则审核将无法通过！</p>
        <el-row>
          <el-col :span="16" :offset="3">
            <el-form-item label="经营品牌类型：" prop="brand_type">
              <el-radio-group v-model="brandForm.brand_type" @change="chooseBrandType">
                <el-radio :label="1">自有品牌</el-radio>
                <el-radio :label="2">品牌厂商授权</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16" :offset="3">
            <el-form-item label="品牌中文名：" prop="brand_cn">
              <el-input v-model="brandForm.brand_cn" @input="checkIsExsitBrandName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16" :offset="3">
            <el-form-item label="品牌英文名：" prop="brand_en">
              <el-input v-model="brandForm.brand_en" placeholder="请输入品牌英文名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16" :offset="3">
            <el-form-item label="品牌商标注册号：" prop="brand_number">
              <el-input v-model="brandForm.brand_number" placeholder=""></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="21" :offset="3">
            <el-form-item label="品牌LOGO：" prop="brand_logo">
              <div style="width:100%;height: 100%;display: flex;flex-direction: row;justify-content: normal;">
                <div style="padding-right:6px;">
                  <el-upload
                    class="uploadData"
                    action="#"
                    list-type="picture-card"
                    :http-request="uploadLogoImgs"
                    :limit="1"
                    :on-exceed="limit1"
                    :before-upload="UpImgSizeFiveKB"
                    :on-preview="handlePreviewLogo"
                    :on-remove="handleRemoveLogo"
                    :file-list='brandImgFileList'
                  >
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <el-dialog :visible.sync="LogoVisible">
                    <img width="100%" :src="LogoImageUrl" alt="">
                  </el-dialog>
                </div>
                <div>
              <span class="tips-text">
                <i class="el-icon-warning h-warning"></i>
              </span>
                </div>
                <div style="width:380px;line-height: 24px;padding-top: 6px;">
                  <span class="tips-text">必须与商标图文一致。文件大小在500KB以内，支持png,jpg格式，最多可上传1张</span>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="21" :offset="3">
            <el-form-item label="商标注册证书：" prop="brand_register_cert">
              <div style="width:100%;height: 100%;display: flex;flex-direction: row;justify-content: normal;">
                <div style="padding-right:6px;">
                  <el-upload
                    class="uploadData"
                    action="#"
                    list-type="picture-card"
                    :http-request="uploadCertImgs"
                    :limit="1"
                    :on-exceed="limit1"
                    :before-upload="UpImgSizeTwoMb"
                    :on-preview="handlePreviewCert"
                    :on-remove="handleRemoveCert"
                    :file-list='certImgFileList'
                  >
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <el-dialog :visible.sync="certVisible">
                    <img width="100%" :src="certImageUrl" alt="">
                  </el-dialog>
                </div>
                <div>
              <span class="tips-text">
                <i class="el-icon-warning h-warning"></i>
              </span>
                </div>
                <div style="width:380px;line-height: 24px;padding-top: 6px;">
                  <span class="tips-text">请提供有效期内的商标注册证，保持信息清晰可见，支持png,jpg格式，最多可上传1张</span>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16" :offset="3">
            <el-form-item label="品牌类型：" prop="brand_range">
              <el-radio-group v-model="brandForm.brand_range" @click="chooseBrandRange">
                <el-radio :label="1">国内品牌</el-radio>
                <el-radio :label="2">国外品牌</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16" :offset="3">
            <el-form-item label="商标注册有效期：" prop="brand_auth_time">
              <el-date-picker type="date" placeholder="选择日期" v-model="validityConcreteTime"
                              style="width: 300px;" @change="validityConcreteChange"></el-date-picker>
              <el-checkbox v-model="validityLongTermVal" style="padding-left:15px;"
                           @change="validityLongTermChange">长期
              </el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16" :offset="3">
            <el-form-item label="品牌授权期限：" prop="brandAuthRangeTime">
              <el-date-picker
                style="width:400px;"
                v-model="brandForm.brandAuthRangeTime"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                :clearable = 'false'
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="21" :offset="3">
            <el-form-item label="品牌厂商授权：" prop="brand_auth" v-if="brandForm.brand_type === 2">
              <div style="width:100%;height: 100%;display: flex;flex-direction: row;justify-content: normal;">
                <div style="padding-right:6px;">
                  <el-upload
                    class="uploadData"
                    action="#"
                    list-type="picture-card"
                    :http-request="uploadFactoryImgs"
                    :before-upload="UpImgSizeTwoMb"
                    :on-preview="handlePreviewFactory"
                    :on-remove="handleRemoveFactory"
                    :file-list='factoryImgFileList'
                  >
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <el-dialog :visible.sync="factoryVisible">
                    <img width="100%" :src="factoryImageUrl" alt="">
                  </el-dialog>
                </div>
                <div>
              <span class="tips-text">
                <i class="el-icon-warning h-warning"></i>
              </span>
                </div>
                <div style="width:380px;line-height: 24px;padding-top: 6px;">
                  <span class="tips-text">授权在云仓平台经营此品牌，支持png,jpg格式，文件大小在2MB以内</span>
                </div>
              </div>
              <p class="brand-auth-tips">上传完整授权链路，品牌方给予企业的授权书，如果是多级授权，请上传各级授权证书</p>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="21" :offset="3">
            <el-form-item label="品牌经营授权：" prop="brand_business_auth">
              <div style="width:100%;height: 100%;display: flex;flex-direction: row;justify-content: normal;">
                <div style="padding-right:6px;">
                  <el-upload
                    class="uploadData"
                    action="#"
                    :http-request="uploadShopImgs"
                    list-type="picture-card"
                    :before-upload="UpImgSizeTwoMb"
                    :on-preview="handlePreviewShop"
                    :on-remove="handleRemoveShop"
                    :file-list="shopImgFileList"
                  >
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <el-dialog :visible.sync="shopVisible">
                    <img width="100%" :src="shopImageUrl" alt="">
                  </el-dialog>
                </div>
                <div>
              <span class="tips-text">
                <i class="el-icon-warning h-warning"></i>
              </span>
                </div>
                <div style="width:380px;line-height: 24px;padding-top: 6px;">
                  <span class="tips-text">授权在云仓平台经营此品牌，支持png,jpg格式</span>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16" :offset="3">
            <el-form-item label="">
              <div style="width:100%;height: 100%;display: flex;flex-direction: row;justify-content: normal;">
                <el-button :disabled="downTemplatehttp !== '' ? false: true" >
                  <el-link :href="downTemplatehttp" :disabled="downTemplatehttp !== '' ? false: true" type="primary" :underline="false"><i class="el-icon-download"></i>下载模板</el-link>
                </el-button>
                <div>
                  <span class="tips-text">
                    <i class="el-icon-warning h-warning"></i>
                  </span>
                </div>
                <div style="width:380px;line-height: 24px;padding-top: 6px;">
                  <span class="tips-text">请您点击下载授权书模板，打印并签字盖章，拍照上传</span>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item class="btnCen">
          <el-button type="" @click="handleCancel" style="margin-right: 30px">取  消</el-button>
          <el-button type="primary" @click="handleSave('brandForm')">提交审核</el-button>
        </el-form-item>

      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import {getBrandsInf, getDetails, addBrandData, upBrand, upLoadImg, delBrandData} from '@/api/module/brand/brand'
  import { dateFormat } from '@/utils'
  export default {
    name: "Brand",
    data() {
      let logoValidator = (rule, value, callback) => {
        if(this.brandImgFileList.length > 0) {
          callback();
        }else if(this.brandImgFileList.length === 0) {
          callback(new Error("品牌logo图片至少上传一张"));
        }
      };
      let certValidator = (rule, value, callback) => {
        if(this.certImgFileList.length > 0) {
          callback();
        }else if(this.certImgFileList.length === 0) {
          callback(new Error("商标注册证书图片至少上传一张"));
        }
      };
      let authValidator = (rule, value, callback) => {
        if(this.factoryImgFileList.length > 0) {
          callback();
        }else if(this.factoryImgFileList.length === 0) {
          callback(new Error("品牌商标授权书图片至少上传一张"));
        }
      };
      let authTimeValidator = (rule, value, callback) => {
        if(this.brandForm.brand_type === 2) {
          if (this.validityConcreteTime === null && this.validityLongTermVal === false) {
            callback(new Error("品牌注册有效期具体时间和长期必须填写其中一个"));
          } else {
            callback();
          }
        }else {
          callback();
        }
      };
      let authRangeTimeValidator = (rule, value, callback) => {
        if( Array.isArray(this.brandForm.brandAuthRangeTime) && this.brandForm.brandAuthRangeTime.length == 2) {
          callback();
        }else {
          callback(new Error("请选择品牌授权期限"));
        }
      };
      let authBusValidator = (rule, value, callback) => {
        if(this.shopImgFileList.length > 0) {
          callback();
        }else if(this.shopImgFileList.length === 0) {
          callback(new Error("品牌logo图片至少上传一张"));
        }
      };
      return {
        fullHeight: 0,
        tableHeight: 0,
        isOpen: false,
        brandTitle: '',
        brandTypeOptions: [
          {label: "全部品牌", value: '-1'},
          {label: "自有品牌", value: '1'},
          {label: "品牌厂商授权", value: '2'},
        ],
        statusOptions: [
          {label: '未审核', value: '0'},
          {label: '已通过', value: '1'},
          {label: '已拒绝', value: '2'},
          {label: '已过期', value: '3'},
        ],
        total: 0,
        queryParams: {
          page: 1,
          limit: 10,
          brand_name: '',
          brand_type: '',
          status: ''
        },
        LogoVisible: false,
        LogoImageUrl: '',
        factoryVisible: false,
        factoryImageUrl: '',
        shopVisible: false,
        shopImageUrl: '',
        certVisible: false,
        certImageUrl: '',
        brandImgFileList: [],// 品牌logo
        certImgFileList: [],// 商标注册证书
        factoryImgFileList: [], // 品牌方授权书
        shopImgFileList: [], //
        validityConcreteTime: null,
        validityLongTermVal: false, // 长期
        brandList: [],
        indexBrandId: 0, // 当前品牌 id
        statusVal: '',
        brandForm: {
          id: 0,
          brand_type: '',  // 品牌经营类型
          brand_cn: '',   // 中文名称
          brand_en: '',   // 英文名称
          brand_logo: '',   // 品牌logo图片
          brand_register_cert: '', // 商标注册证书
          brand_number: '',   // 品牌商标注册号
          brand_range: '',   // 品牌类型
          brand_auth_time: '',   // 商品注册有效期
          brandAuthRangeTime: [], // 品牌授权有效期
          brand_auth: '',  // 商标授权 == 品牌授权 == factoryImgFileList
          brand_business_auth: '', // 商标经营授权 == 品牌经营授权 == shopImgFileList
        },
        brandRules: {
          brand_type: [{ required: true, message: '品牌经营类型需要选择其一', trigger: 'blur' }],
          brand_cn: [{ required: true, message: '品牌中文名称不能为空', trigger: 'blur' }],
          brand_number: [{ required: true, message: '品牌商标注册号不能为空', trigger: 'blur' }],
          brand_logo: [{ required: true, message: '品牌logo图片至少上传一张',validator: logoValidator}],
          brand_register_cert: [{ required: true, message: '商标注册证书图片至少上传一张',validator: certValidator}],
          brand_range: [{ required: true, message: '品牌类型需要选择其一', trigger: 'blur' }],
          brand_auth: [{ required: true, message: '品牌授权书图片至少上传一张', validator: authValidator}], // 品牌授权
          brand_auth_time: [{ required: true,trigger: 'change',validator:authTimeValidator }],
          brandAuthRangeTime: [{ required: true,trigger: 'blur',validator:authRangeTimeValidator }],
          brand_business_auth: [{ required: true, message: '品牌经营授权至少上传一张图片', validator: authBusValidator }],
        },
        downTemplatehttp: '',
        shopTemplatehttp : 'http://excel.jxhh.com/brand_new.doc',
        factoryTemplatehttp : 'http://excel.jxhh.com/brand_new.doc',
      }
    },
    created() {
      this.getList();
      this.$nextTick(() => {
        this.fullHeight = document.getElementsByClassName('box-card')[0].clientHeight;
      })
    },
    watch: {
      fullHeight(val) {
        let formHeight = document.getElementsByClassName('clearfix')[0].clientHeight
        this.tableHeight = val - formHeight - 100;
      }
    },

    methods: {
      /** 查询 品牌 列表 */
      getList() {
        let data = {
          page: this.queryParams.page,
          limit: this.queryParams.limit
        }
        if (this.queryParams.brand_name != "") {
          data['brand_name'] = this.queryParams.brand_name
        }
        if (this.queryParams.brand_type == '1' || this.queryParams.brand_type == '2' || this.queryParams.brand_type == '3') {
          data['brand_type'] = this.queryParams.brand_type
        }
        if (this.queryParams.status == '0' || this.queryParams.status == '1' || this.queryParams.status == '2') {
          data['status'] = this.queryParams.status
        }
        getBrandsInf(data).then(res => {
          if ( res.code == 1) {
            if(res.data) {
              this.brandList = res.data.data;
              this.total = res.data.count;
            }else {
              this.brandList = [];
            }
          }else {
            this.$message({ type: 'error',message: res.message ? res.message : '获取品牌列表数据失败' });
          }
        });
      },
      /** 品牌 审核状态 */
      statusFormatter(status) {
        let res = '';
        if (status == 0) {
          res = '等待审核'
        }
        if (status == 1) {
          res = '审核通过'
        }
        if (status == 2) {
          res = '审核被拒绝'
        }
        return res
      },
      /** 校验品牌 */
      checkIsExsitBrandName() {
        if (!this.brandForm.brand_cn) return
        let data = {
          brand_name : this.brandForm.brand_cn
        }
        getDetails(data).then(res=> {
          if (res.code == 1 && res.data) {
            this.$message({ type: 'warning', message: '品牌名称已存在'});
          }
        });
      },
      /** 新增 品牌 */
      addBrand() {
        // if(this.total <= 20 ) {
          this.isOpen = true;
          this.brandTitle = '新增品牌信息';
          this.indexBrandId = 0;
          this.reset('brandForm')
        // }else {
        //   this.$message({ type: 'warning', message: '目前暂时只支持维护20个品牌数据'});
        // }
      },
      /** 编辑 品牌 */
      editBrand(row) {
        this.indexBrandId = row.id;
        let data = {
          id : this.indexBrandId
        }
        getDetails(data).then(res => {
          if(res.code == 1) {
            this.isOpen = true;
            this.brandTitle = '品牌信息详情';
            this.brandForm = res.data;
            // 品牌审核状态
            this.statusVal = this.statusFormatter(res.data.status)
            // 模板下载地址赋值
            this.downTemplatehttp = (this.brandForm.brand_type === 1 ? this.shopTemplatehttp : this.factoryTemplatehttp);

            // 品牌logo图片
            let brandArr = [];
            let brandUrl = {};
            brandArr = this.brandForm.brand_logo.split(",");
            if (brandArr.length > 0) {
              brandArr.forEach(item=> {
                brandUrl = {};
                if (item) {
                  brandUrl.url = item
                  this.brandImgFileList.push(brandUrl)
                }
              });
            }else {
              this.brandImgFileList = [];
            }

            // 商标注册证书图片
            let certArr = [];
            let certRrl = {};
            certArr = this.brandForm.brand_register_cert.split(",");
            if (certArr.length > 0) {
              certArr.forEach(item=> {
                certRrl = {};
                if (item) {
                  certRrl.url = item
                  this.certImgFileList.push(certRrl)
                }
              });
            }else {
              this.certImgFileList = [];
            }

            // 商标注册有效期
            if(this.brandForm.brand_auth_time === 0) {
              this.validityLongTermVal = true;
              this.validityConcreteTime = '';
            }else {
              this.validityLongTermVal = false;
              this.validityConcreteTime = this.timeFormatter(this.brandForm.brand_auth_time);
            }

            // 品牌授权期限
            this.$set(this.brandForm,'brandAuthRangeTime',[this.timeFormatter(this.brandForm.brand_start_time),this.timeFormatter(this.brandForm.brand_end_time)]);

            // 品牌厂商授权 图片
            let factoryArr = [];
            let factoryUrl = {};
            factoryArr = this.brandForm.brand_auth.split(",");
            if (factoryArr.length > 0) {
              factoryArr.forEach(item=> {
                factoryUrl = {};
                if (item) {
                  factoryUrl.url = item
                  this.factoryImgFileList.push(factoryUrl)
                }
              });
            }else {
              this.factoryImgFileList = [];
            }

            // 品牌经营授权 图片
            let shopArr = [];
            let shopUrl = {};
            shopArr = this.brandForm.brand_business_auth.split(",");
            if (shopArr.length > 0) {
              shopArr.forEach(item=> {
                shopUrl = {};
                if (item) {
                  shopUrl.url = item
                  this.shopImgFileList.push(shopUrl)
                }
              });
            }else {
              this.shopImgFileList = [];
            }

          }else {
            this.$message({type: 'error',message: res.message ? res.message : '获取品牌失败' });
          }

        });
      },
      /** 取消、关闭  新增，编辑 */
      handleCancel() {
        this.reset('brandForm')
        this.isOpen = false;
      },
      /** 提交審核 */
      handleSave(form) {
        this.$refs[form].validate(valid => {
          if(valid) {
            // 入参数据
            let brandsData = { brands: [] };
            let data = {}
            data['id'] = this.indexBrandId;
            data['brand_type'] = this.brandForm.brand_type;
            data['brand_cn'] = this.brandForm.brand_cn;
            data['brand_en'] = this.brandForm.brand_en;
            data['brand_number'] = this.brandForm.brand_number;

            // 品牌logo图片处理
            if(this.brandImgFileList.length > 0) {
              for(let i = 0; i < this.brandImgFileList.length; i++) {
                if(i === 0) {
                  data['brand_logo'] = this.brandImgFileList[i].url;
                }else {
                  data['brand_logo'] += ',' + this.brandImgFileList[i].url;
                }
              }
            }

            // 商标注册证书图片
            if(this.certImgFileList.length > 0) {
              for(let a = 0; a < this.certImgFileList.length; a++) {
                if(a === 0) {
                  data['brand_register_cert'] = this.certImgFileList[a].url;
                }else {
                  data['brand_register_cert'] += ',' + this.certImgFileList[a].url;
                }
              }
            }
            // 品牌类型
            data['brand_range'] = this.brandForm.brand_range

            // 商标注册有效期
            if (this.validityLongTermVal) {
              data['brand_auth_time'] = 0;
            }else {
              data['brand_auth_time'] = new Date(this.validityConcreteTime).getTime() / 1000;
            }

            // 品牌 授权期限
            if (Array.isArray(this.brandForm.brandAuthRangeTime) && this.brandForm.brandAuthRangeTime.length == 2) {
              data['brand_start_time'] = new Date(this.brandForm.brandAuthRangeTime[0]).getTime() / 1000;
              data['brand_end_time'] = new Date(this.brandForm.brandAuthRangeTime[1]).getTime() / 1000;
            }

            // 品牌商标授权 图片
            if(this.factoryImgFileList.length > 0) {
              for(let i = 0; i < this.factoryImgFileList.length; i++) {
                if(i === 0) {
                  data['brand_auth'] = this.factoryImgFileList[i].url;
                }else {
                  data['brand_auth'] += ',' + this.factoryImgFileList[i].url;
                }
              }
            }

            // 品牌经营授权 图片处理
            if(this.shopImgFileList.length > 0) {
              for(let i = 0; i < this.shopImgFileList.length; i++) {
                if(i === 0) {
                  data['brand_business_auth'] = this.shopImgFileList[i].url;
                }else {
                  data['brand_business_auth'] += ',' + this.shopImgFileList[i].url;
                }
              }
            }

            // 新增 品牌
            if (this.indexBrandId == 0) {
              // 入参 格式处理
              brandsData.brands.push(data);

              addBrandData(brandsData).then(res => {
                if(res.code == 1) {
                  this.$message({ message: '提交成功', type: 'success'});
                  this.getList();
                  this.isOpen = false;
                }else {
                  this.$message({ type: 'error', message: res.message ? res.message : "提交失败"});
                }
              });
            }

            // 修改 品牌
            if (this.indexBrandId != 0) {
              this.$confirm('确定要提交审核吗？提交审核后，品牌处于待审核状态，对应商品将做下架处理', '提示：', {
                type: 'warning',
                confirmButtonText: '确定',
                cancelButtonText: '取消'
              }).then(async() => {
                let res = await upBrand(data)
                if ( res.code == 1 ) {
                  this.$message({ message: '提交成功', type: 'success'});
                  this.getList();
                  this.isOpen = false;
                }else {
                  this.$message({ type: 'error', message: res.message ? res.message : "提交失败"});
                }
              }).catch(() => {});
            }

          } // vilid end
        })
      },


      /** 删除 品牌 */
      deleteBrand(row) {
        if (!row.id) { return }
        let data = {
          brand_ids: []
        }
        data.brand_ids.push(row.id);

        this.$confirm('确定要删除品牌吗？品牌删除后，使用该品牌的商品也会作下架处理！', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async() => {
          let result = await delBrandData(data);
          if(result.code == 1) {
            this.$message({type:'success',message:'删除成功'});
            this.getList()
          }else {
            this.$message({type:'error',message: result.message ? result.message : '删除成功'});
          }
        }).catch(()=> {});
      },
      /** 查询 */
      handleQuery() {
        this.queryParams.page = 1;
        this.getList();

      },
      /** 商品注册有效期 具体时间 */
      validityConcreteChange() {
        if (this.validityConcreteTime) {
          this.validityLongTermVal = false;
        }
      },
      /** 商品注册有效期 长期 */
      validityLongTermChange() {
        if (this.validityLongTermVal) {
          this.validityConcreteTime = null;
        }
      },
      // 通用方法
      /** 重置 编辑 表单*/
      reset(formName){
        this.brandImgFileList= [];
        this.certImgFileList= [];
        this.factoryImgFileList= [];
        this.shopImgFileList= [];

        this.validityLongTermVal = false;
        this.validityConcreteTime = ''
        Object.assign(this.brandForm, this.$options.data().brandForm)

        if (this.$refs[formName]) {
          this.$refs[formName].resetFields();
        }else {
          this.$nextTick(()=> {
            this.$refs[formName].resetFields();
          })
        }

        // console.log("brandForm:",this.brandForm);
      },
      /** 上传图片 数量限制 */
      limit1() {
        this.$message({message: '最多上传1张图片', type: 'warning'});
      },
      /** 时间格式化 */
      timeFormatter(timeVal) {
        return dateFormat(timeVal *1000, 'Y-m-d')
      },
      /** 品牌 状态格式化 */
      brandStatusFormatter(statusVal) {
        let res = '';
        if (statusVal == 0) {
          res = '未审核'
        }
        if (statusVal == 1) {
          res = '已通过'
        }
        if (statusVal == 2) {
          res = '已拒绝'
        }
        if (statusVal == 3) {
          res = '已过期'
        }

        return res;
      },
      /** 图片转换为base64位 */
      getBase64(file) {
        return new Promise(function(resolve, reject) {
          let reader = new FileReader();
          let imgResult = "";
          reader.readAsDataURL(file);
          reader.onload = function() {
            imgResult = reader.result;
          };
          reader.onerror = function(error) {
            reject(error);
          };
          reader.onloadend = function() {
            resolve(imgResult);
          };
        });
      },

      /**********---------------------------------------------************************** */
      // 品牌经营类型 改变触发
      chooseBrandType() {
        this.downTemplatehttp = '';
        // 因 单选不能取消，所以，只要点击触发，即可清除校验
        this.$refs.brandForm.clearValidate('brand_type');
        // 自有品牌授权模板下载路径 shopTemplatehttp
        // 品牌厂商授权模板下载路径 factoryTemplatehttp
        this.downTemplatehttp = (this.brandForm.brand_type === 1 ? this.shopTemplatehttp : this.factoryTemplatehttp);
        //
        // 品牌授权 图片处理   factoryImgFileList
        if(this.brandForm.brand_auth === '') {
          this.factoryImgFileList = [];
        }
      },
      chooseBrandRange() {
        this.$refs.brandForm.clearValidate('brand_range');
      },

      // 品牌商标图片  自定义上传
      uploadLogoImgs(param) {
        this.getBase64(param.file).then((res) => {
          let result = res.split(",");
          this.Base64img = result[1];
          let data = {"img_data": this.Base64img};
          upLoadImg(data).then((res) => {
            if (res && res.code === 1) {
              this.brandImgFileList.push({'url': res.data.image_url});
              this.$message({message: '上传成功', type: 'success'});
              this.$refs.brandForm.clearValidate('brand_logo');
              //this.$refs.logoImg.clearValidate();
            }
          });
        });
      },
      // 上传图片格式和大小限制500 kb
      UpImgSizeFiveKB(file) {
        let isImgSize = (file.size / 1024 ) > 500;
        if(file.type !== "image/png" && file.type !== "image/jpg" && file.type != "image/jpeg") {
          this.$message({
            message: '上传图片格式只支持jpg/png格式',
            type: "warning"
          });
          return false;
        }
        if(isImgSize) {
          this.$message({
            message: '上传图片大小不能超过500 kb',
            type: "warning"
          });
          return false;
        }
      },
      // logo 预览
      handlePreviewLogo(file) {
        this.LogoImageUrl = file.url;
        this.LogoVisible = true;
      },
      // logo 删除
      handleRemoveLogo(file) {
        for(let i = 0; i < this.brandImgFileList.length; i++) {
          if(file.uid === this.brandImgFileList[i].uid) {
            this.brandImgFileList.splice(i,1);
          }
        }
      },
      // 商标注册证书
      uploadCertImgs(param) {
        this.getBase64(param.file).then((res) => {
          let result = res.split(",");
          this.Base64img = result[1];
          let data = {"img_data": this.Base64img};
          upLoadImg(data).then((res) => {
            if (res && res.code === 1) {
              this.certImgFileList.push({'url': res.data.image_url});
              this.$message({message: '上传成功', type: 'success'});
              this.$refs.brandForm.clearValidate('brand_register_cert');
              //this.$refs.logoImg.clearValidate();
            }
          });
        });
      },
      // 预览
      handlePreviewCert(file) {
        this.certImageUrl = file.url;
        this.certVisible = true;
      },

      // 删除
      handleRemoveCert(file) {
        for(let i = 0; i < this.certImgFileList.length; i++) {
          if(file.uid === this.certImgFileList[i].uid) {
            this.certImgFileList.splice(i,1);
          }
        }
      },

      // 品牌方授权书 自定义上传
      uploadFactoryImgs(param) {
        this.getBase64(param.file).then((res) => {
          let result = res.split(",");
          this.Base64img = result[1];
          let data = {"img_data":this.Base64img};
          upLoadImg(data).then((res) => {
            if(res && res.code ===  1){
              this.factoryImgFileList.push({'url':res.data.image_url});
              this.$refs.brandForm.clearValidate('brand_auth');
              this.$message({message: '上传成功', type: 'success'});
            }
          });
        });
      },
      // 上传图片格式和大小限制 2mb
      UpImgSizeTwoMb(file) {
        if(file.type !== "image/png" && file.type !== "image/jpg" && file.type != "image/jpeg") {
          this.$message({
            message: '上传图片格式只支持jpg/png格式',
            type: "warning"
          });
          return false;
        }
        let isImgSize = (file.size / 1024 /1024) > 2;
        if(isImgSize) {
          this.$message({
            message: '上传图片大小不能超过2M',
            type: "warning"
          });
          return false;
        }
      },
      // 预览
      handlePreviewFactory(file) {
        this.factoryImageUrl = file.url;
        this.factoryVisible = true;
      },
      // 删除
      handleRemoveFactory(file) {
        for(let i = 0; i < this.factoryImgFileList.length; i++) {
          if(file.uid === this.factoryImgFileList[i].uid) {
            this.factoryImgFileList.splice(i,1);
          }
        }
      },
      // 品牌经营授权图片上传
      uploadShopImgs(param) {
        this.getBase64(param.file).then((res) => {
          let result = res.split(",");
          this.Base64img = result[1];
          let data = {"img_data":this.Base64img};
          upLoadImg(data).then((res) => {
            if(res && res.code ===  1){
              this.shopImgFileList.push({'url':res.data.image_url});
              this.$message({message: '上传成功', type: 'success'});
              this.$refs.brandForm.clearValidate('brand_business_auth');
            }
          });
        });
      },
      // 预览
      handlePreviewShop(file) {
        this.shopImageUrl = file.url;
        this.shopVisible = true;
      },
      // 删除
      handleRemoveShop(file) {
        for(let i = 0; i < this.shopImgFileList.length; i++) {
          if(file.uid === this.shopImgFileList[i].uid) {
            this.shopImgFileList.splice(i,1);
          }
        }
      },
    } // methods end
  }
</script>

<style lang="scss" type="text/stylus" scoped>
  .brandInf-add {
    /deep/.el-dialog {
      height: 85%;
      overflow : hidden;
    }
    /deep/.el-dialog__body{
      height: calc(100% - 60px);
      overflow-x: hidden;
      overflow-y: scroll;
    }
  }

  .brand-status-con {
    font-size: 16px;
    margin: 0 10% 10px;
    padding: 12px 20px;
    border: 1px solid #00afff;
    display : flex;
    justify-content : normal;
    align-items :center;
    flex-direction : row;
  }
  .color-spe-success {
    color: #67C23A;
    font-size: 20px;
    padding-top: 2px;
  }
  .color-spe-error {
    color: #F56C6C;
    font-size: 20px;
    padding-top: 2px;
  }
  .color-spe-waiting {
    color: #909399;
    font-size: 20px;
    padding-top: 2px;
  }

  .brand-form-status-text {
    padding: 0 10px;
  }
  .btnCen {
    /deep/.el-form-item__content {
      margin-left: 0!important;
      text-align : center;
      margin-top: 30px;
    }
  }

  .brand-title-tips {
    text-align : center;
    padding: 10px 20px 20px;
    margin: 0;
    font-size : 14px;
    color: #F56C6C;
  }

  .brand-auth-tips {
    margin: 0;
    font-size : 12px;
    color: #F56C6C;
  }

  .brand-refused-title {
    margin: 0 8px;
    font-size: 18px;
  }

// 上传图片样式重置 start
  .uploadData {
    display: inline-block;
    /deep/ .el-upload--picture-card {
      width: 100px;
      height: 100px;
    }

    /deep/ .el-upload {
      width: 100px;
      height: 100px;
      line-height: 100px;
    }

    /deep/ .el-upload-list--picture-card .el-upload-list__item {
      width: 100px;
      height: 100px;
      line-height: 100px;
    }

    /deep/ .el-upload-list--picture-card .el-upload-list__item-thumbnail {
      width: 100px;
      height: 100px;
      line-height: 100px;
    }

    /deep/ .avatar {
      width: 100px;
      height: 100px;
    }
  }
// 上传图片样式 重置 end
// 提示语 样式 start
  .tips-text {
    font-size: 14px;
    color: #C9C9C9;
    word-break: break-all;
  }

  .h-warning:before {
    color: #e3c300;
  }
// 提示语样式  end
</style>
