<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_cn"
                  placeholder="请输品牌名称"
                  clearable
                  size="small"
                />
              </el-form-item>

              <el-form-item label="品牌经营类型：">
                <el-select v-model="queryParams.brand_type" clearable size="small" placeholder="全部品牌类型" @change="typeChange">
                  <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="全部状态" @change="statusChange">
                  <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="handleAdd">新 增</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-table v-loading="loading" :data="brandList" :height="tableHeight">
<!--        <el-table-column type="selection" width="45" align="center"/>-->
        <el-table-column label="序号" prop="id" align="center"></el-table-column>
        <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_range" align="center">
          <template slot-scope="scope">
            {{ scope.row.brand_range === 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">
            {{ scope.row.status === 0 ? '未审核' : scope.row.status === 1 ? '已通过' : '已拒绝'}}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="handleDetails(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="60%" class="brandInf-add">
      <el-form :model="brandForm" :rules="brandRules" ref="brandForm" label-width="140px">
        <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"></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="2"
                    :on-exceed="limitTwo"
                    :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格式，最多可上传2张</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="2"
                    :on-exceed="limitTwo"
                    :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">品牌方给予企业的授权书。文件大小在2MB以内，支持png,jpg格式</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="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">品牌方给予企业的授权书。文件大小在2MB以内，支持png,jpg格式</span>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="16" :offset="3">
            <el-form-item label="授权有效期至：" prop="brand_auth_time" v-if="brandForm.brand_type === 2">
              <el-date-picker type="date" placeholder="选择日期" v-model="validityConcreteTime"
                              style="width: 300px;" @change="validityConcrete"></el-date-picker>
              <el-checkbox v-model="validityLongTermVal" style="padding-left:15px;"
                           @change="validityLongTerm">长期
              </el-checkbox>
            </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">授权在云仓平台经营此品牌。文件大小在2MB以内，支持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('brandForm')" 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, addBrand, upBrand, upLoadImg} from '@/api/module/brand/brand'

  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 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,
        loading: false,
        isOpen: false,
        brandTitle: '',
        brandTypeOptions: [
          {label: "自有品牌", value: 1},
          {label: "品牌厂商授权", value: 2},
        ],
        statusOptions: [
          {label: '未审核', value: 0},
          {label: '已通过', value: 1},
          {label: '已拒绝', value: 2}
        ],
        total: 0,
        queryParams: {
          page: 1,
          limit: 10,
          brand_cn: null,
          brand_type: null,
          status: null
        },
        LogoVisible: false,
        LogoImageUrl: '',
        factoryVisible: false,
        factoryImageUrl: '',
        shopVisible: false,
        shopImageUrl: '',
        certVisible: false,
        certImageUrl: '',
        brandImgFileList: [],// 品牌logo
        certImgFileList: [],// 商标注册证书
        factoryImgFileList: [], // 品牌方授权书
        shopImgFileList: [], //
        validityConcreteTime: null,
        validityLongTermVal: false, // 长期
        brandList: [],
        brandForm: {
          id: 0,
          brand_type: '',  // 品牌经营类型
          brand_cn: '',   // 中文名称
          brand_en: '',   // 英文名称
          brand_logo: '',   // 品牌logo图片
          brand_register_cert: '', // 商标注册证书
          brand_number: '',   // 品牌商标注册号
          brand_range: '',   // 品牌类型
          brand_auth_time: '',   // 授权有效期  == 商标授权时间期限
          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 }],
          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',
        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: {
      typeChange(val){
        if(val === "") {
          this.queryParams.brand_type = null;
        }
      },
      statusChange(val){
        if(val === "") {
          this.queryParams.status = null;
        }
      },
      isClick() {
        return false;
      },
      getList() {
        this.loading = true;
        //let params = this.handleQueryParams(this.queryParams);
        getBrandsInf(this.queryParams).then(res => {
          if ( res && res.data && res.code === 1) {
            if(res.data) {
              this.brandList = res.data.data;
              this.total = res.data.count;
            }else {
              this.brandList = [];
            }
          }else {
            this.$message({ message: '数据出错啦！', type: 'error'});
          }
          this.loading = false;
        });
      },

      // 品牌经营类型 改变触发
      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');
      },
      limitTwo() {
        this.$message({message: '最多上传2张图片', type: 'warning'});
      },
      // 品牌商标图片  自定义上传
      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);
          }
        }
      },

      // 授权有效期 二选一效果
      validityConcrete() {
        if (this.validityConcreteTime) {
          this.validityLongTermVal = false;
        }
      },
      validityLongTerm() {
        if (this.validityLongTermVal) {
          this.validityConcreteTime = null;
        }
      },

      // 新增，修改，详情
      handleAdd() {
        if(this.total < 20 ) {
          this.isOpen = true;
          this.brandTitle = '新增品牌信息';
          this.reset('brandForm');
          this.brandForm.id = 0;
          this.brandForm.brand_auth = '';
          this.brandForm.brand_auth_time = '';
        }else {
          this.$message({ type: 'warning', message: '目前暂时只支持维护20个品牌数据！'});
        }
      },
      // 详情
      handleDetails(row) {
        this.isOpen = true;
        this.brandTitle = '品牌信息详情';
        const ids = row.id;
        getDetails(ids).then(res => {
          if(res.code && res.code === 1 && res.data) {
            this.brandForm = res.data;
            // 模板下载地址赋值
            this.downTemplatehttp = (this.brandForm.brand_type === 1 ? this.shopTemplatehttp : this.factoryTemplatehttp);
            // 商标logo图片处理
            let brandList = {};
            let brandArr = [];
            if(this.brandForm.brand_logo.indexOf(",") > 0) {
              brandArr = this.brandForm.brand_logo.split(",");
              for(let a = 0; a < brandArr.length; a++){
                brandList = {};
                brandList.url = brandArr[a];
                this.brandImgFileList.push(brandList);
              }
            }else {
              brandList.url = this.brandForm.brand_logo;
              this.brandImgFileList = [];
              this.brandImgFileList.push(brandList);
            }

            // 商标注册证书处理 brand_register_cert
            let certList = {};
            let certArr = [];
            if(this.brandForm.brand_register_cert.indexOf(",") > 0) {
              certArr = this.brandForm.brand_register_cert.split(",");
              for(let a = 0; a < certArr.length; a++){
                certList = {};
                certList.url = certArr[a];
                this.certImgFileList.push(certList);
              }
            }else {
              certList.url = this.brandForm.brand_register_cert;
              this.certImgFileList = [];
              this.certImgFileList.push(certList);
            }

            // 品牌授权 图片处理   factoryImgFileList
            let factoryList = {};
            let factoryArr = [];
            if(this.brandForm.brand_auth.indexOf(",") > 0) {
              factoryArr = this.brandForm.brand_auth.split(",");
              for(let authIndex = 0; authIndex < factoryArr.length; authIndex++){
                factoryList = {};
                factoryList.url = factoryArr[authIndex];
                this.factoryImgFileList.push(factoryList);
              }
            }else {
              factoryList.url = this.brandForm.brand_auth;
              this.factoryImgFileList = [];
              this.factoryImgFileList.push(factoryList);
            }

            // 品牌经营授权 图片处理  shopImgFileList
            let shopList = {};
            let shopArr = [];
            if(this.brandForm.brand_business_auth.indexOf(",") > 0) {
              shopArr = this.brandForm.brand_business_auth.split(",");
              for(let busIndex = 0; busIndex < shopArr.length; busIndex++){
                shopList = {};
                shopList.url = shopArr[busIndex];
                this.shopImgFileList.push(shopList);
              }
            }else {
              shopList.url = this.brandForm.brand_business_auth;
              this.shopImgFileList = [];
              this.shopImgFileList.push(shopList);
            }

            // 期限处理
            if(this.brandForm.brand_auth_time === 0) {
              this.validityLongTermVal = true;
            }else {
              this.validityConcreteTime = this.toStandTime(this.brandForm.brand_auth_time);
            }
          }else if(res.code === 0) {
            if(res.msg) {
              this.$message({message: res.msg, type: 'error'});
            }else {
              this.$message({message: '数据出错啦！', type: 'error'});
            }
          }
        });
      },
      // 查询
      handleQuery() {
        this.queryParams.page = 1;
        this.getList();
      },
      // 保存
      handleSave(form) {
        this.$refs[form].validate(valid => {
          if(valid) {
            let addBrandForm = {};
            let toArrBrandForm = [];
            if(this.validityLongTermVal) {
              this.brandForm.brand_auth_time = (this.validityLongTermVal - 0 - 1);
            }else if(this.validityLongTermVal === false && this.validityConcreteTime) {
              this.brandForm.brand_auth_time = new Date(this.validityConcreteTime).getTime() / 1000;
            }else {
              this.brandForm.brand_auth_time = '';
            }
            // 品牌logo图片处理
            if(this.brandImgFileList.length > 0) {
              for(let i = 0; i < this.brandImgFileList.length; i++) {
                if(i === 0) {
                  this.brandForm.brand_logo = this.brandImgFileList[i].url;
                }else {
                  this.brandForm.brand_logo += ',' + this.brandImgFileList[i].url;
                }
              }
            }
            // 商标注册证书图片处理 certImgFileList
            if(this.certImgFileList.length > 0) {
              for(let i = 0; i < this.certImgFileList.length; i++) {
                if(i === 0) {
                  this.brandForm.brand_register_cert = this.certImgFileList[i].url;
                }else {
                  this.brandForm.brand_register_cert += ',' + this.certImgFileList[i].url;
                }
              }
            }
            // 品牌授权图片处理
            if(this.factoryImgFileList.length > 0) {
              for(let i = 0; i < this.factoryImgFileList.length; i++) {
                if(i === 0) {
                  this.brandForm.brand_auth = this.factoryImgFileList[i].url;
                }else {
                  this.brandForm.brand_auth += ',' + this.factoryImgFileList[i].url;
                }
              }
            }
            // 品牌经营授权 图片处理
            if(this.shopImgFileList.length > 0) {
              for(let i = 0; i < this.shopImgFileList.length; i++) {
                if(i === 0) {
                  this.brandForm.brand_business_auth = this.shopImgFileList[i].url;
                }else {
                  this.brandForm.brand_business_auth += ',' + this.shopImgFileList[i].url;
                }
              }
            }

            // 数据处理完毕
            toArrBrandForm.push(this.brandForm);
            addBrandForm.brands = toArrBrandForm;

            // 新增/修改
            if(this.brandForm.id === 0) {
              addBrand(addBrandForm).then(res => {
                if(res.code && res.code === 1) {
                  this.$message({ message: '新增成功', type: 'success'});
                  this.getList();
                  this.reset('brandForm');
                  this.isOpen = false;
                }else if( res.code === 0) {
                  if(res.msg) {
                    this.$message({ message: res.msg, type: 'error'});
                  }else {
                    this.$message({ message: '新增失败', type: 'error'});
                  }
                }
              });
            // 修改
            }else {
              this.$confirm('是否确认修改此数据项？', '提示：', {
                type: 'warning',
                confirmButtonText: '确定',
                cancelButtonText: '取消'
              }).then(() => {
                this.edit(toArrBrandForm);
              }).catch(() => {
                this.isOpen = false;
              });
            }
          }
        })
      },

      // 修改
      edit(param) {
        upBrand(param).then(res => {
          if(res.code === 1) {
            this.$message({ message: '修改成功', type: 'success'});
            this.getList();
          }else if( res.code === 0 ) {
            if(res.msg) {
              this.$message({
                message: res.msg,
                type: 'error'
              });
            }else {
              this.$message({
                message: '数据出错啦！',
                type: 'error'
              });
            }
          }
          this.reset('brandForm');
          this.isOpen = false;
        });
      },
      // 取消
      handleCancel(form) {
        this.reset(form);
        this.isOpen = false;
      },

      // -----------通用 方法----------
      // 搜索参数处理
      handleQueryParams(parmas) {
        let newParmas = {};
        // 对象深拷贝
        newParmas = JSON.parse(JSON.stringify(parmas));
        for(let key in newParmas){
          if(key) {
            if(newParmas[key] !== 0 && newParmas[key] !== '') {
              if(!newParmas[key]) {
                newParmas[key] = null;
              }
            }
          }
        }
        return newParmas;
      },
      // 究极清空
      reset(form){
        if(this.$refs[form]) {
          this.$refs[form].resetFields();
        }else {
          this.$nextTick(() => {
            this.$refs[form].resetFields();
          });
        }
        // 取消按钮，图片清空
        this.brandImgFileList= [];
        this.certImgFileList= [];
        this.factoryImgFileList= [];
        this.shopImgFileList= [];
      },

      // 图片转换为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);
          };
        });
      },
      // 时间戳转换为 标准时间格式
      toStandTime(val) {
        let date = new Date(val * 1000)
        let Y = date.getFullYear() + '-'
        let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
        const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
        const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
        const m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
        const s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds())
        return Y + M + D + h + m + s;
      },
    }
  }
</script>

<style lang="scss" type="text/stylus" scoped>
  .brandInf-add {
    /deep/.el-dialog {
      height: 80%;
      overflow : hidden;
    }
    /deep/.el-dialog__body{
      height: calc(100% - 60px);
      overflow-x: hidden;
      overflow-y: scroll;
    }
  }
  .btnCen {
    /deep/.el-form-item__content {
      margin-left: 0!important;
      text-align : center;
      margin-top: 30px;
    }
  }

// 上传图片样式重置 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>
