<template>
  <div class="block">
    <div class="head">
      <div class="go-back" @click="goBack">
        <i class="el-icon-back"></i>返回上一页
      </div>
    </div>

    <div class="body">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-alert
          title="基础信息"
          type="info"
          :closable="false"
          style="margin-bottom: 10px"
        ></el-alert>

        <el-form-item label="产品名称" prop="name">
          <el-input
            class="half-width"
            v-model="ruleForm.name"
            placeholder="请输入产品名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="产品缩略图" prop="coverImg">
          <!-- 上传 -->
          <my-upload
            :value="ruleForm.coverImg"
            @input="(val, info) => getSrc('coverImg', val)"
          ></my-upload>
        </el-form-item>
        <el-form-item label="上传源文件">
          <!-- :prop="'imageInfoRelationList.url' && 'imageInfoRelationList.price'" -->

          <!-- 上传 -->
          <!-- <my-upload
            refName="upload2"
            :value="ruleForm.imageInfoRelationList.url"
            @input="(val, info) => getSrc('imageInfoRelationList', val, info)"
          ></my-upload> -->

          <!-- <div v-if="ruleForm.imageInfoRelationList.fileWidth">
            尺寸大小：{{ ruleForm.imageInfoRelationList.fileWidth }}
          </div> -->
          <!-- <el-input
            class="half-width"
            size="small"
            v-model="ruleForm.imageInfoRelationList.price"
            placeholder="请输入价格"
          ></el-input> -->
          <el-upload
            class="upload-demo"
            :action="BASE_API + '/api/datacenter/bg/gtdata/upload'"
            :on-success="handleDataUpSuccess"
            :headers="getHeaderWithToken"
            :show-file-list="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <el-row
            style="
              display: flex;
              align-items: center;
              margin-top: 10px;
              box-sizing:border-box;
              margin-bottom:5px
              border-bottom: 1px solid #f4f4f5;
            "
            v-for="(item, idx) in ruleForm.imageInfoRelationList"
            :key="idx"
          >
            <el-col :span="3" style="display: flex; align-items: center">
              <span>{{ item.url | filterUrl }}</span>
            </el-col>
            <el-col :span="6" style="display: flex; align-items: center">
              <label>尺寸:&nbsp;</label>
              <el-input
                v-model="item.fileWidth"
                placeholder="请输入尺寸大小"
                style="width: 60%"
              ></el-input>
            </el-col>
            <el-col :span="6" style="display: flex; align-items: center">
              <label>价格:&nbsp;</label>
              <el-input-number
                style="width: 80%"
                v-model="item.price"
                :min="0"
                :step="0.01"
                :precision="2"
              ></el-input-number>
            </el-col>
            <el-col :span="4">
              <el-button
                @click="del_dataImgItem(idx)"
                type="primary"
                icon="el-icon-delete"
                >删除</el-button
              >
            </el-col>
          </el-row>
        </el-form-item>

        <el-alert
          title="产品参数"
          type="info"
          :closable="false"
          style="margin-bottom: 10px"
        ></el-alert>

        <el-form-item label="影像分类" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择">
            <el-option
              v-for="(item, index) in imageTypes"
              :key="~~index"
              :label="item"
              :value="~~index"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品类型" prop="paramJson.productType">
          <el-input
            class="half-width"
            v-model="ruleForm.paramJson.productType"
            placeholder="请输入产品类型"
          ></el-input>
        </el-form-item>
        <el-form-item label="文件格式" prop="paramJson.productType">
          <el-input
            class="half-width"
            v-model="ruleForm.paramJson.fileType"
            placeholder="请输入文件格式"
          ></el-input>
        </el-form-item>
        <el-form-item label="卫星" prop="paramJson.satellite">
          <el-input
            class="half-width"
            v-model="ruleForm.paramJson.satellite"
            placeholder="请输入卫星型号"
          ></el-input>
        </el-form-item>
        <el-form-item label="分辨率" prop="paramJson.resolution">
          <el-input
            class="half-width"
            v-model="ruleForm.paramJson.resolution"
            placeholder="请输入产品分辨率"
          ></el-input>
        </el-form-item>
        <el-form-item label="拍摄地点" prop="paramJson.address">
          <el-input
            class="half-width"
            v-model="ruleForm.paramJson.address"
            placeholder="请输入拍摄地点"
          ></el-input>
        </el-form-item>
        <el-form-item label="拍摄时间" prop="paramJson.shotTime">
          <el-date-picker
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="ruleForm.paramJson.shotTime"
            type="datetime"
            placeholder="选择日期时间"
            :picker-options="datePickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="可否商用" prop="paramJson.commercial">
          <el-radio-group v-model="ruleForm.paramJson.commercial">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否水印" prop="paramJson.watermark">
          <el-radio-group v-model="ruleForm.paramJson.watermark">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="相似图片" prop="relatedIds">
          <el-button
            type="primary"
            icon="el-icon-plus"
            @click="showImagesDialog"
            >相似图片</el-button
          >
          <el-tag type="success">已选 {{ images.selects.length }}个</el-tag>
        </el-form-item>
        <el-form-item label="产品介绍">
          <kind-editor
            id="editor_id"
            :content.sync="ruleForm.intro"
            :afterChange="afterChange()"
            :loadStyleMode="false"
            @on-content-change="onContentChange"
          ></kind-editor>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确定</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 相似图片弹窗 -->
    <el-dialog
      title="相似图片"
      :visible.sync="images.visible"
      width="80%"
      :close-on-click-modal="false"
    >
      <el-row :gutter="20">
        <el-col :span="6" v-for="item in images.datas" :key="item.id">
          <div
            :class="`grid-content${
              selectsArr.includes('' + item.id) ? ' active' : ''
            }`"
            @click="select(item)"
          >
            <el-image :src="item.url" lazy></el-image>
          </div>
        </el-col>
      </el-row>
      <div
        style="
          margin-top: 10px;
          display: flex;
          align-item: center;
          justify-content: center;
        "
      >
        <el-pagination
          small
          layout="prev, pager, next"
          :page-size="images.pageInfo.limit"
          :total="images.total"
          @current-change="currentChange"
        >
        </el-pagination>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="confirm">确 定</el-button>
        <el-button @click="images.visible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import MyUpload from "@/components/Upload/singleImageX"; //上传组件

import { update, getAll, getDetail } from "@/api/website/imageLibrary";
import KindEditor from "@/components/Kindeditor";
import { getToken } from "utils/auth";
export default {
  components: {
    MyUpload,
    KindEditor,
  },
  filters: {
    filterUrl: function (val) {
      if (val) {
        let idx = val.lastIndexOf("/");
        return val.substring(idx + 1, val.length);
      }
    },
  },
  data() {
    let checkNumber = function (rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入价格"));
      } else {
        if (isNaN(value)) {
          callback(new Error("请输入数字"));
        } else {
          callback();
        }
      }
    };
    return {
      BASE_API: process.env.BASE_API,
      //1--影像美图 2--专题图 3--遥感成果图
      imageTypes: {
        1: "影像美图",
        2: "专题图",
        3: "遥感成果图",
      },
      ruleForm: {
        name: "",
        coverImg: "",
        imageInfoRelationList: [],
        intro: "",
        type: "",
        relatedIds: "",
        paramJson: {
          productType: "",
          fileType: "",
          satellite: "",
          resolution: "",
          address: "",
          shotTime: "",
          commercial: "",
          watermark: "",
        },
      },
      rules: {
        name: [{ required: true, message: "请输入产品名称", trigger: "blur" }],
        coverImg: [
          { required: true, message: "请上传缩略图", trigger: "change" },
        ],
        type: [
          { required: true, message: "请选择影像类型", trigger: "change" },
        ],
        "paramJson.productType": [
          { required: true, message: "请输入产品类型", trigger: "blur" },
        ],
        "paramJson.fileType": [{ required: true, message: "请输入文件格式" }],
        "paramJson.satellite": [
          { required: true, message: "请输入卫星型号", trigger: "blur" },
        ],
        "paramJson.resolution": [
          { required: true, message: "请输入分辨率", trigger: "blur" },
        ],
        "paramJson.address": [
          { required: true, message: "请输入拍摄地点", trigger: "blur" },
        ],
        "paramJson.shotTime": [
          { required: true, message: "请选择拍摄时间", trigger: "change" },
        ],
        "paramJson.commercial": [
          { required: true, message: "请选择", trigger: "change" },
        ],
        "paramJson.watermark": [
          { required: true, message: "请选择", trigger: "change" },
        ],
      },
      images: {
        pageInfo: {
          page: 1,
          limit: 20,
        },
        total: 100,
        datas: [],
        visible: false,
        selects: [],
      },
      selectsArr: [],
      datePickerOptions: {
        disabledDate: (time) => {
          return (
            time.getTime() >
            new Date(
              new Date(new Date().toLocaleDateString()).getTime() +
                24 * 60 * 60 * 1000 -
                1
            )
          );
        },
      },
    };
  },
  computed: {
    getHeaderWithToken() {
      return { Authorization: getToken() };
    },
  },
  mounted() {
    //获取所有相似图像
    this.getAllImages();
    this.$bus.$on("imageLibrary-edit-renderData", this.renderData);
  },
  beforeDestroy() {
    this.$bus.$off("imageLibrary-edit-renderData");
  },
  methods: {
    del_dataImgItem(idx) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.ruleForm.imageInfoRelationList.splice(idx, 1);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleDataUpSuccess(res, file) {
      this.ruleForm.imageInfoRelationList.push({
        url: res.data.path,
        price: 0,
        fileWidth: "",
        fileSize: res.data.size,
      });
    },
    afterChange() {},
    onContentChange(val) {
      this.ruleForm.intro = val;
    },
    //打开相似图片dialog弹窗
    showImagesDialog() {
      // console.log(this.images.selects)
      this.selectsArr = JSON.parse(JSON.stringify(this.images.selects));
      this.images.visible = true;
    },
    //相似图片弹窗图片列表切换页面方法
    currentChange(val) {
      this.images.pageInfo.page = val;
      this.getAllImages();
    },
    //选择相似图片确定按钮
    confirm() {
      this.images.visible = false;
      this.ruleForm.relatedIds = this.selectsArr.toString();
      this.images.selects = JSON.parse(JSON.stringify(this.selectsArr));
    },
    //选择相似图片
    select(item) {
      let selects = this.selectsArr;
      let index = selects.indexOf(item.id + "");
      if (index > -1) {
        selects.splice(index, 1);
      } else {
        selects.push(item.id + "");
      }
      this.selectsArr = selects;
    },
    //获取所有相似图像
    getAllImages() {
      getAll(this.images.pageInfo).then((res) => {
        this.images.datas = res.data.data;
        this.images.total = res.data.totalCount;
      });
    },
    //上传图片，获取图片地址
    getSrc(key, val, info) {
      let rule = ["imageInfoRelationList"];

      if (rule.includes(key) && info) {
        this.ruleForm[key] = {
          url: val,
          price: this.ruleForm[key].price,
          fileWidth: info.width + "*" + info.height,
          fileSize: info.size,
        };

        this.$set(this.ruleForm.paramJson, "fileType", info.type);
      } else {
        this.ruleForm[key] = val;
      }
    },
    //点击编辑的时候，获取表格行数据，渲染edit页面
    renderData(params) {
      //获取详情
      let val = params;
      let afterFormat = this.filterParams(val);
      let data = JSON.parse(JSON.stringify(afterFormat));
      console.log(data);
      // data.paramJson = JSON.parse(data.paramJson);
      //注意：imageInfoRelationListParse为imageInfoRelationList参数的最后一项，赋值显示
      data.imageInfoRelationList = data.imageInfoRelationListParse;
      data.coverImg = data.coverImg || "";
      this.ruleForm = data;
      this.images.selects = this.ruleForm.relatedIds.split(","); //相似图片转为数组格式
    },
    //返回上一页
    goBack() {
      this.$emit("change", "List");
    },
    //过滤多余属性
    filterParams(obj) {
      let p = {};
      let b = [
        "isDel",
        "status",
        "updTime",
        "crtTime",
        "allowCustom",
        "rank",
        "relationId",
        "similarImageList",
      ];
      for (let key in obj) {
        if (!b.includes(key)) {
          if (key === "imageInfoRelationList") {
            let temp = this.filterParams(obj[key]);
            obj[key] = [temp];
          }

          p[key] = obj[key];
        }
      }
      return p;
    },
    //提交
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          console.log("submit");
          this.updateFunc(); //上传数据
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //添加/修改方法
    updateFunc() {
      //转换数据格式
      let params = JSON.parse(JSON.stringify(this.ruleForm));

      params.paramJson = JSON.stringify(params.paramJson);
      // params.imageInfoRelationList = [params.imageInfoRelationList];

      console.log(params);
      //执行方法
      update(params).then((res) => {
        if (res.status == 200) {
          //返回上一页，更新列表
          this.goBack();
        } else {
          this.$message.error(res.message);
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.head {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 20px;
  width: 100%;
  border-bottom: 1px solid #e6e6e6;
  .go-back {
    height: 30px;
    line-height: 30px;
    font-size: 16px;
    color: #1989fa;
    cursor: pointer;
    i {
      margin-right: 10px;
    }
  }
}
.body {
  padding: 20px 50px 40px;
}
.grid-content {
  border: 1px solid transparent;
}
.grid-content:hover,
.grid-content.active {
  border: 1px solid #409eff;
  box-sizing: border-box;
}
.half-width {
  width: 50%;
}
.dataImg {
  width: 80px;
  height: 80px;
  border-radius: 5px;
}
</style>
