<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: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:admin:add']"
        >新增</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="adminList" height="calc(100vh - 28vh)">
      <!-- <el-table-column label="单位编号" align="center" prop="ownerId"/> -->
      <el-table-column label="单位名称" align="center" prop="name" show-overflow-tooltip/>
      <!-- <el-table-column label="所属建筑id" align="center" prop="buildingId" />
      <el-table-column label="单位联系人" align="center" prop="contacts" /> -->
      <el-table-column label="单位介绍" align="center" prop="remark" show-overflow-tooltip/>
      <el-table-column label="公司LOGO">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.logo"
            style="width: 50px; height: 50px"
            :preview-src-list="['https://smartpark.caih.com/dmapi/archive/' + scope.row.logo]"
            :src="'https://smartpark.caih.com/dmapi/archive/' + scope.row.logo">
          </el-image>
  　　</template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" show-overflow-tooltip/>
      <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:admin:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @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-table-column label="单位名称" align="center" prop="ownerName" />
      <el-table-column label="所属建筑id" align="center" prop="buildingId" />
      <el-table-column label="单位联系人" align="center" prop="contacts" />
      <el-table-column label="联系电话" align="center" prop="contactsPhone" />
      <el-table-column label="创建人" align="center" prop="createMan" />
      <el-table-column label="创建时间" align="center" prop="createTime" /> -->

        <el-form-item label="单位名称" prop="name" >
          <el-input v-model.trim="form.name" placeholder="请输入单位名称" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="单位介绍" prop="remark">
          <el-input type="textarea" :rows="4" placeholder="请输入单位介绍" v-model.trim="form.remark" maxlength="80" show-word-limit >
          </el-input>
        </el-form-item>

        <el-form-item label="单位LOGO" prop="logo" ref="img">
          <el-upload
            class="upload-demo"
            action="#"
            :limit = 1
            :on-change="handleChange"
            :file-list="fileList"
            >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
      </el-form-item>
          <!-- <el-checkbox-group v-model="form.logo" v-show="false"></el-checkbox-group> -->
            <!-- <el-upload
              action="#"
              accept="image/png,image/jpg,image/jpeg"
              :http-request="uploadFile"
              :limit = limit
              list-type="picture-card"
              :file-list="fileList"
              style="color:#D9D9D9"
              on-sucsee="handSuccess"
              :auto-upload="true">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                  <img class="el-upload-list__item-thumbnail imgupload" :src="file.url" alt="" >
                  <span class="el-upload-list__item-actions">
                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
            </el-upload> -->
          <!-- <el-dialog :visible.sync="dialogVisible" >
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog> -->
      </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 { addProduct, updataProduct, delProduct, listProduct } from "@/api/system/product";
import { fileUpload } from "@/api/business/uploadfile.js";
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.$nextTick(() => {
      //       this.$refs['form'].clearValidate(['logo']);
      //   })
      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;
      listProduct(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.form.batchNo =undefined
      this.reset();
      this.open = true;
      this.title = "添加参数";
      setTimeout(()=>{
        document.getElementsByClassName("el-upload--picture-card")[0].style.display="block"
      },200)
    },
    // 多选框选中数据
    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 = "修改参数";
      setTimeout(() =>{
        if(this.fileList.length>0){
        }else{
          this.fileList.push([])
          this.fileList[0].url = row.logo
        }
        document.getElementsByClassName("el-upload--picture-card")[0].style.display="none"
      },100)
      this.limit = 1
      // });
    },
    // 图片上传尺寸大小检验
    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);
        };
      });
    },
    uploadFile(param){
      this.limit = 1
      document.getElementsByClassName("el-upload--picture-card")[0].style.display="none"
      fileId().then(res=>{
        this.$nextTick(() => {
            this.$refs['form'].clearValidate(['logo']);
        })
        this.form.batchNo = res.msg
        this.form.logo = res.msg
        this.formData = new FormData()// FormData 对象
        this.formData.append('files', param.file)// 文件对象
      })
    },
    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
          // // 上传图片
          // 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) {
                  updataProduct(this.form).then(response => {
                    this.loading = false,
                    this.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                  }).catch(()=>{
                    this.loading = false,
                    this.open = false
                  })
                } else {
                  addProduct(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 delProduct(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      refreshCache().then(() => {
        this.msgSuccess("刷新成功");
      });
    },
    handleChange(param){
      this.num++
      if(this.num>1){
        this.num = 0
        return false
      }else{
        const formData = new FormData();
        formData.append('file', param.raw)
        formData.append('multipart', param.raw)
        fileUpload(formData).then(response => {
          this.msgSuccess("上传成功");
          this.form.logo = response.data
        });
      }
    },
  }
};
</script>
<style lang="scss" scoped>
// .el-button--primary{color:#50B300;border:1px solid #50B300;background: #fff;}
// .el-button--primary:hover{color:#fff;border:1px solid #50B300;background: #50B300;}
</style>

