<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="公司名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入公司名称"
          clearable
          size="small"
          style="width: 140px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary"  size="mini" @click="handleQuery">搜索</el-button>
        <el-button
          type="primary"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:admin:add']"
        >新增</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="adminList" >
      <el-table-column label="序号" align="center" prop="" show-overflow-tooltip >
        <template slot-scope="scope">
         {{scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column label="公司名称" align="center" prop="name" show-overflow-tooltip/>
      <el-table-column label="公司介绍" align="center" prop="introduce" show-overflow-tooltip />
      <el-table-column label="公司LOGO">
        <template width="90" slot-scope="scope" >
           <el-image
            v-if="scope.row.logo"
            style="width: 80px"
            :preview-src-list="[scope.row.logo]"
            :src="scope.row.logo">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime"  show-overflow-tooltip >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            class="lans"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:admin:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            class="hongs"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:admin:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog   :title="title" :visible.sync="open" width="600px" append-to-body :before-close="cancel" :close-on-click-modal="false"  >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" >
        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="公司名称" prop="name" >
              <el-input v-model="form.name" placeholder="请输入公司名称" />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="公司介绍" prop="introduce">
              <el-input type="textarea" :rows="4" placeholder="请输入公司介绍" v-model="form.introduce">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位LOGO" prop="logo" ref="img">
              <el-upload
                class="upload-demo"
                action="#"
                :limit = 1
                :on-change="handleChange"
                :file-list="fileList"
                :auto-upload="false"
                accept=".jpg,.jpeg,.JPG,.JPEG,.PNG,.png,.GIF,.gif"
                >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
         </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-if="!loading">确 定</el-button>
          <el-button :loading="loading" type="primary" @click="submitForm" v-else>提交中...</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>

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

<script>
import { addChannel, updataChannel, delChannel, listChannel, fileId, uploadFileApi, fileTakeEffect, getFile } from "@/api/system/product";
export default {
  name: "admin",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      dialogFormVisible:false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 图片显示
      fileList:[{"url":''}],
      // 参数表格数据
      adminList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型数据字典
      typeOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        name: undefined,
        aliasName: undefined,
      },
      // 表单参数
      form: {
        id:'',
        name:'',
        introduce:'',
        logo:"",
        batchNo:undefined,
        businessType:"产品logo",
        uploadType:"file",
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "公司名称不能为空", trigger: "blur" }
        ],
        logo: [
          { required: true, message: "公司logo不能为空", trigger: "change" }
        ],
      },
      //  上传图片
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      imageInfo: {},
      imageList: [],
      formInline: {
          image64: "",
          imageName: "",
      },
      formData:undefined,
      limit:100,
      num:0,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleRemove(file) {
      this.form.logo = undefined
      this.limit = 100
      document.getElementsByClassName("el-upload-list el-upload-list--picture-card")[0].firstChild.remove()
      document.getElementsByClassName("el-upload--picture-card")[0].style.display="block"
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      listChannel(this.addDateRange(this.queryParams)).then(response => {
        if(response.data.records.length>0){
          let arrBig = response.data.records
          let arr = []
          arr = response.data.records.map(item =>{
            return {
              batchNos:[item.logo]
            }
          })
          for(let i=1;i<response.data.records.length; i++){
            arr[0].batchNos.push(response.data.records[i].logo)
          }
          getFile(arr[0]).then(response =>{
            const reverse = response.data.reverse()
            for(let i=0;i<response.data.length;i++){
              arrBig[i].logo = reverse[i].url
            }
          })
          setTimeout(()=>{
            this.loading = false;
            this.adminList = arrBig;
            this.total = response.data.total;
            this.logo = arrBig.logo;
          },1000)

        }else{
          this.adminList = []
          this.loading = false;
        }
      })
    },
    // 移出图片
    removeImg(){
      this.form.logo = undefined
      setTimeout(()=>{
        this.limit = 100
        this.fileList=[]
      },1000)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ids: undefined,
        name: undefined,
        aliasName: undefined,
        adminType: "Y",
      };
      this.fileList=[]
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.form.id =undefined
      this.form.name =undefined
      this.form.introduce =undefined
      this.form.logo =undefined
      this.reset();
      this.open = true;
      this.title = "添加参数";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      Object.assign(this.form, row.id ? this.adminList.find(val=>val.id === row.id) : this.adminList.find(val=>val.id === this.ids[0]))
      this.open = true;
      this.title = "修改参数";
    },
    // 图片上传尺寸大小检验
    beforeUpload (file) {
      const is1M = file.size /  1024 < 70; // 限制小于70kb
      const isSize = new Promise(function (resolve, reject) {
        let width = 1024; // 限制图片尺寸为1024X240
        let height = 640;
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function () {
          let valid = img.width === width && img.height === height;
          valid ? resolve() : reject();
        }

        img.src = _URL.createObjectURL(file);
      }).then(() => {
        return file;
      }, () => {
        this.$message.error('图片尺寸限制为1024 x 240，大小不可超过70kB')
        return Promise.reject();
      });
      // if (!is1M) {
      //   this.$message.error('图片尺寸限制为1024 x 240，大小不可超过70kB')
      // }
      // return isSize&is1M
    },
     // 图片 转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);
        };
      });
    },
    handleChange(param){
      this.limit = 1
      this.num++
      if(this.num>1){
        this.num = 0
        return false
      }else{
        fileId().then(res=>{ //获取文件批号
          this.$nextTick(() => {
              this.$refs['form'].clearValidate(['logo']);
          })
          this.form.batchNo = res.data
          this.form.logo = res.data
          this.formData = new FormData()// FormData 对象
          this.formData.append('files', param.raw)
        })
      }
    },
    handSuccess(){
      this.$refs.img.clearValidate();
    },
     //变化设置图片
    onChange(file, fileList) {
      this.form.file = fileList;
    },
    /** 提交按钮 */
    submitForm(row) {
      if(this.form.logo){
      }else{
          this.$refs.img.clearValidate();
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true
          // 上传图片
          this.form.businessType = "产品logo",
          uploadFileApi(this.form.batchNo,this.form.businessType,this.formData).then(response => {
            if(response.data.length>0){
              let ids = new FormData()
              ids.append('ids[]', response.data[0].id)
              // 上传图片生效
              fileTakeEffect(response.data[0].batchNo,ids).then(response => {
                // this.msgSuccess("上传成功");
                if (this.form.id != undefined) {
                  updataChannel(this.form).then(response => {
                    this.loading = false,
                    this.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                  }).catch(()=>{
                    this.loading = false,
                    this.open = false
                  })
                } else {
                  addChannel(this.form).then(response => {
                    this.loading = false,
                    this.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                  }).catch(()=>{
                    this.loading = false,
                    this.open = false
                  })
                }
              }).catch(err =>{
              })
            }
          })
          .catch((e) => {
            this.$message.error('上传失败')
            this.getList();
          })
          // this.removeImg()
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delChannel(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      refreshCache().then(() => {
        this.msgSuccess("刷新成功");
      });
    }
  }
};
</script>


