<!--
 * @Author: your name
 * @Date: 2020-12-04 09:09:37
 * @LastEditTime: 2020-12-11 16:52:41
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \rs-cloud-platform-ui\src\views\webSiteManagement\industryApplication\applicationList\addApp\index.vue
-->
<template>
  <div id="addApp">
    <div class="top">
      <div class="title" @click="backup">
        <i class="el-icon-back"></i>
        <!-- <img src="/static/images/return.png"/> -->
        返回上一页
      </div>
    </div>
    <div class="content">
      <el-form ref="form" :rules="rules" :model="form" label-width="120px">
        <div class="item">
          <div class="title">基本信息</div>
          <div class="form">
            <el-form-item
              label="应用类别"
              prop="type"
              v-show="firstTypes.length > 0"
            >
              <el-select v-model="currentFirstType" placeholder="全部">
                <el-option
                  v-for="item in firstTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <el-select v-model="currentSecondType" placeholder="全部">
                <el-option
                  v-for="item in secondTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="应用名称" prop="title">
              <el-col :span="12">
                <el-input
                  v-model="form.title"
                  placeholder="请输入应用名称"
                ></el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="封面图" prop="coverImg">
              <singleImageX
                :value="form.coverImg"
                @input="onCoverPreview"
              ></singleImageX>
            </el-form-item>
            <el-form-item label="详情图" prop="detailImg">
              <singleImageX
                :value="form.detailImg"
                @input="onDetailPreview"
              ></singleImageX>
            </el-form-item>
          </div>
        </div>
        <div class="item">
          <div class="title">应用参数</div>
          <div class="form">
            <el-form-item label="行业" prop="industry">
              <el-col :span="12">
                <el-input
                  v-model="form.industry"
                  placeholder="请输入行业"
                ></el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="地区" prop="region">
              <el-col :span="12">
                <el-input
                  v-model="form.region"
                  placeholder="请输入地区"
                ></el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="数据采集时间" prop="collectTime">
              <el-col :span="12">
                <el-input
                  v-model="form.collectTime"
                  placeholder="请输入数据采集时间"
                ></el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="数据来源" prop="origin">
              <el-col :span="12">
                <el-input
                  v-model="form.origin"
                  placeholder="请输入数据来源"
                ></el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="成果形式" prop="achievement">
              <el-col :span="12">
                <el-input
                  v-model="form.achievement"
                  placeholder="请输入成果形式"
                ></el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="分辨率" prop="resolvpower">
              <el-col :span="12">
                <el-input
                  v-model="form.resolvpower"
                  placeholder="请输入分辨率"
                ></el-input>
              </el-col>
            </el-form-item>
            <el-form-item label="价格" prop="price">
              <el-col :span="12">
                <el-input-number
                  v-model="form.price"
                  :min="0"
                  :step="0.01"
                  :precision="2"
                  placeholder="请输入价格"
                ></el-input-number>
              </el-col>
            </el-form-item>
            <el-form-item label="是否提供样例" prop="isSample">
              <el-radio-group v-model="form.isSample">
                <el-radio-button label="是"></el-radio-button>
                <el-radio-button label="否"></el-radio-button>
              </el-radio-group>
            </el-form-item>
            <!-- <el-form-item label="是否提供定制" prop="isCustomized">
              <el-radio-group v-model="form.isCustomized">
                <el-radio-button label="是"></el-radio-button>
                <el-radio-button label="否"></el-radio-button>
              </el-radio-group>
            </el-form-item> -->
            <el-form-item label="上传样例" prop="fileList">
              <el-upload
                class="upload-demo"
                action="#"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                multiple
                :on-exceed="handleExceed"
                :http-request="onUploadRequest"
                :file-list="form.fileList"
              >
                <el-button size="small" type="primary">上传文件</el-button>
                <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
              </el-upload>
            </el-form-item>
            <el-form-item label="上传源文件" prop="sourceFile">
              <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;
            "
              >
                <el-col :span="3" style="display: flex; align-items: center">
                  <span>{{ form.sourceFile | filterUrl }}</span>
                </el-col>
              </el-row>
            </el-form-item>
          </div>
        </div>
        <div class="item">
          <div class="title">应用简介</div>
          <div class="form">
            <el-form-item label="产品简介" prop="introduction">
              <kind-editor
                id="editor_id"
                :content.sync="form.introduction"
                :afterChange="afterChange()"
                :loadStyleMode="false"
                @on-content-change="onContentChange"
              ></kind-editor>
            </el-form-item>
          </div>
        </div>
        <el-form-item>
          <el-button @click="$parent.componentName = 'appList'">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 使用图片查看器预览当前缩略图 -->
    <el-image-viewer
      v-if="currentIcon.showPreview"
      :on-close="closePreview"
      :url-list="[currentIcon.url]"
    />
  </div>
</template>

<script>
// 导入组件
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
import { uploadFile } from "@/api/website/newsCategory/index";
import singleImageX from "@/components/Upload/singleImageX";
import KindEditor from "@/components/Kindeditor";
import {
  getAllApplicationType,
  addUpdateApplicationInfo,
} from "api/website/industryApplication/index";
import { getToken } from "utils/auth";
export default {
  name: "addApp",
  components: {
    singleImageX,
    KindEditor,
    ElImageViewer,
  },
  filters: {
    filterUrl: function (val) {
      if (val) {
        let idx = val.lastIndexOf("/");
        return val.substring(idx + 1, val.length);
      }
    },
  },
  data() {
    return {
      BASE_API: process.env.BASE_API,
      rules: {
        type: [{ required: true, message: "请选择应用类别", trigger: "blur" }],
        title: [{ required: true, message: "请输入应用名称", trigger: "blur" }],
        coverImg: [
          { required: true, message: "请上传封面图", trigger: "blur" },
        ],
        detailImg: [
          { required: true, message: "请上传详情图", trigger: "blur" },
        ],
        price: [{ required: true, message: "请输入价格", trigger: "blur" }],
        industry: [{ required: true, message: "请输入行业", trigger: "blur" }],
        region: [{ required: true, message: "请输入地区", trigger: "blur" }],
        collectTime: [
          { required: true, message: "请输入数据采集时间", trigger: "blur" },
        ],
        origin: [
          { required: true, message: "请输入数据来源", trigger: "blur" },
        ],
        achievement: [
          { required: true, message: "请输入成果形式", trigger: "blur" },
        ],
        resolvpower: [
          { required: true, message: "请输入分辨率", trigger: "blur" },
        ],
        isSample: [
          { required: true, message: "是否提供样例", trigger: "blur" },
        ],
        // isCustomized: [
        //   { required: true, message: "是否提供定制", trigger: "blur" },
        // ],
        fileList: [{ required: true, message: "请上传样例", trigger: "blur" }],
        sourceFile: [
          { required: true, message: "请上传源文件", trigger: "blur" },
        ],
        introduction: [
          { required: true, message: "请输入产品简介", trigger: "blur" },
        ],
      },
      form: {
        price: 0, //价格
        title: "", // 应用名称
        coverImg: "", // 封面图
        detailImg: "", // 详情图
        industry: "", // 行业
        region: "", // 地区
        collectTime: "", // 采集时间
        origin: "", // 数据来源
        achievement: "", // 成果形式
        resolvpower: "", // 分辨率
        isSample: "是", // 是否提供样例
        // isCustomized: "是", // 是否定制
        fileList: [], // 样例图片路径集合
        introduction: "", // 简介
        sourceFile: "", //源文件路径
      },
      currentIcon: {
        showPreview: false,
        url: [],
      },
      firstTypes: [],
      currentFirstType: "",
      secondTypes: [],
      currentSecondType: "",
    };
  },
  watch: {
    "form.fileList": {
      deep: true,
      handler: function (newVal) {
        console.log("newVal=>", newVal);
      },
    },
  },
  computed: {
    getHeaderWithToken() {
      return { Authorization: getToken() };
    },
  },
  mounted() {
    this.pullAllApplicationType();
    if (!!this.$parent.info) {
      let info = this.$parent.info;
      let attribute = eval("(" + info.attribute + ")");
      console.log("info=>", info);
      console.log("获取到的编辑数据=>", attribute);
      this.form.title = info.title;
      this.form.coverImg = info.coverImg;
      this.form.detailImg = info.icon.url;
      console.log(info);
      this.form.price = info.price;
      this.form.sourceFile = info.sourceFile;
      this.form.industry = attribute.industry;
      this.form.region = attribute.area;
      this.form.collectTime = attribute.date;
      this.form.origin = attribute.source;
      this.form.achievement = attribute.achievements;
      this.form.resolvpower = attribute.ratio;
      this.form.isSample = info.examples == 0 ? "否" : "是";
      this.form.fileList =
        info.examples != 0 ? eval("(" + info.examplesJson + ")") : [];
      this.form.introduction = info.introduction;
      // this.form.isCustomized = info.customized == 1 ? "是" : "否";
      // this.form = {
      //   title: info.title,// 应用名称
      //   coverImg: info.coverImg,// 封面图
      //   detailImg: info.icon.url,// 详情图
      //   industry: attribute.industry,// 行业
      //   region: attribute.area,// 地区
      //   collectTime: attribute.date,// 采集时间
      //   origin: attribute.source,// 数据来源
      //   achievement: attribute.achievements,// 成果形式
      //   resolvpower: attribute.ratio,// 分辨率
      //   isCustomized: '是',// 是否定制
      //   isSample: info.examples==0?"是":"否",// 是否提供样例
      //   fileList: info.examples==0?eval("("+info.examplesJson+")"):[],// 样例图片路径集合
      //   introduction: info.introduction, // 简介
      // }
    }
    this.$bus.$emit("hideThreeRoute", false);
  },
  beforeDestroy() {
    this.$bus.$emit("hideThreeRoute", true);
  },
  methods: {
    handleDataUpSuccess(res, file) {
      this.form.sourceFile = res.data.path;
    },
    // 获取所有应用类型
    pullAllApplicationType() {
      this.firstTypes = [];
      getAllApplicationType().then((res) => {
        if (res.status == 200) {
          res.data.forEach((element) => {
            if (element.isDel == 0) {
              if (element.pid == 0) {
                this.firstTypes.push({
                  value: element.id,
                  label: element.title,
                });
              } else {
                this.secondTypes.push({
                  value: element.id,
                  label: element.title,
                });
              }
            }
          });
          if (this.firstTypes.length > 0) {
            this.currentFirstType = this.firstTypes[0].value;
          }
          if (this.secondTypes.length > 0) {
            this.currentSecondType = this.secondTypes[0].value;
          }
        }
      });
    },
    // 关闭图片查看器
    closePreview() {
      this.currentIcon.showPreview = false;
    },
    onContentChange(val) {
      console.log(val);
    },
    afterChange() {},
    backup() {
      this.$parent.componentName = "appList";
      this.$bus.$emit("hideThreeRoute", true);
    },
    // 上传样例Begin
    onUploadRequest(data) {
      /**
       * [{"filename":"文件名","size":"文件大小","url":"文件路径"}]
       */
      console.log("uploadData=>", data);
      let filename = data.file.name;
      let size = data.file.size;
      let fileObj = data.file;
      //获取图片详情信息
      let imgInfo = {};
      let temp = URL.createObjectURL(fileObj);
      let img = new Image();
      img.src = temp;
      img.onload = function () {
        imgInfo.width = img.width;
        imgInfo.height = img.height;
      };
      imgInfo.size = fileObj.size;
      imgInfo.type = fileObj.type;
      // FormData 对象
      let form = new FormData();
      // 文件对象
      form.append("file", fileObj);
      uploadFile(form).then((res) => {
        this.uploading = false;
        if (res.status == 200) {
          console.log("上传文件成功,获取到的文件路径为=>", res.data);
          this.form.fileList.push({
            name: filename,
            size: size,
            url: res.data,
          });
        } else {
          this.$message.error(res.message);
        }
      });
    },
    handlePreview(file, fileList) {
      let obj = this.form.fileList.find((element) => element.name == file.name);
      let url = obj ? obj.url : "";
      console.log("url=>", url);
      this.currentIcon.showPreview = true;
      this.currentIcon.url = url;
    },
    handleRemove(file, fileList) {
      let index = this.form.fileList.findIndex((ele) => ele.name == file.name);
      index != -1 && this.form.fileList.splice(index, 1);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    // 上传样例End
    onCoverPreview(url) {
      this.form.coverImg = url;
    },
    onDetailPreview(url) {
      this.form.detailImg = url;
    },
    onSubmit() {
      if (this.form.title == "") {
        this.$message.error("请输入应用名称!!!");
      } else if (this.form.coverImg == "") {
        this.$message.error("请上传封面图!!!");
      } else if (this.detailImg == "") {
        this.$message.error("请上传详情图!!!");
      } else if (this.form.introduction == "") {
        this.$message.error("请输入产品简介!!!");
      } else if (this.form.industry == "") {
        this.$message.error("请输入行业!!!");
      } else if (this.form.region == "") {
        this.$message.error("请输入地区!!!");
      } else if (this.form.achievement == "") {
        this.$message.error("请输入成果形式!!!");
      } else if (this.form.origin == "") {
        this.$message.error("请输入数据来源!!!");
      } else if (this.form.collectTime == "") {
        this.$message.error("请输入数据采集时间!!!");
      } else if (this.form.resolvpower == "") {
        this.$message.error("请输入分辨率!!!");
      } else if (this.form.isSample == "是" && this.form.fileList.length == 0) {
        this.$message.error("请上传样例!!!");
      } else if (this.form.sourceFile == "") {
        this.$message.error("请上传源文件!!!");
      } else {
        let data, message;
        if (this.$parent.info) {
          data = {
            id: this.$parent.info.id,
            title: this.form.title,
            coverImg: this.form.coverImg,
            detailImg: this.form.detailImg,
            price: this.form.price,
            sourceFile: this.form.sourceFile,
            introduction: this.form.introduction,
            attribute: JSON.stringify({
              industry: this.form.industry,
              area: this.form.region,
              achievements: this.form.achievement,
              source: this.form.origin,
              date: this.form.collectTime,
              ratio: this.form.resolvpower,
            }),
            examples: this.form.isSample == "是" ? 1 : 0,
            examplesJson: JSON.stringify(this.form.fileList),
            protection: this.$parent.protection,
            rank: this.$parent.info.rank,
            status: this.$parent.info.status,
            firstTypeId: this.$parent.info.firstTypeId,
            firstTitle: this.$parent.info.firstTitle,
            secondTypeId: this.$parent.info.secondTypeId,
            secondTitle: this.$parent.info.secondTitle,
            indexShow: this.$parent.info.indexShow,
            isDel: this.$parent.info.isDel,
            // customized: this.form.isCustomized == "是" ? 1 : 2,
          };
          message = "修改成功!!!";
        } else {
          let secondtitle = "";
          if (this.secondTypes && this.currentSecondType) {
            secondtitle = this.secondTypes.find(
              (ele) => ele.value == this.currentSecondType
            ).label;
          }
          data = {
            title: this.form.title,
            coverImg: this.form.coverImg,
            detailImg: this.form.detailImg,
            introduction: this.form.introduction,
            price: this.form.price,
            sourceFile: this.form.sourceFile,
            attribute: JSON.stringify({
              industry: this.form.industry,
              area: this.form.region,
              achievements: this.form.achievement,
              source: this.form.origin,
              date: this.form.collectTime,
              ratio: this.form.resolvpower,
            }),
            examples: this.form.isSample == "是" ? 1 : 0,
            examplesJson: JSON.stringify(this.form.fileList),
            protection: "",
            indexShow: 1,
            isDel: 0,
            status: 1,
            rank: 0,
            firstTypeId: this.currentFirstType,
            firstTitle: this.firstTypes.find(
              (ele) => ele.value == this.currentFirstType
            ).label,
            secondTypeId: this.currentSecondType,
            secondTitle: secondtitle,
            // customized: this.form.isCustomized == "是" ? 1 : 2,
          };
          message = "添加成功!!!";
        }
        addUpdateApplicationInfo(data).then((res) => {
          if (res.status == 200) {
            this.$message({
              message: message,
              type: "success",
            });
            this.$parent.componentName = "appList";
            this.$parent.info = null;
          } else {
            this.$message.error("操作失败,请稍后重试!!!");
          }
        });
      }
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
#addApp {
  margin: 0 1% 0 1%;
  width: 98%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  color: #5178f2;
  .top {
    width: 100%;
    height: 68px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    overflow: hidden;
    border-bottom: 1px solid #eeeeee;
    .title {
      width: auto;
      margin: 0 0 0 30px;
      height: 46px;
      display: flex;
      flex-direction: row;
      justify-content: center;
      align-items: center;
      color: #5178f2;
      overflow: hidden;
      cursor: pointer;
    }
  }
  .content {
    width: 100%;
    height: auto;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    .item {
      width: 100%;
      height: auto;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      .title {
        padding-left: 40px;
        width: calc(100% - 40px);
        height: 36px;
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        background-color: #f2f2f2;
        color: #000000;
      }
      .form {
        padding-top: 20px;
        padding-left: 20px;
        width: calc(100% - 40px);
        height: auto;
      }
    }
  }
}
</style>
