<template>
  <div>
      <div class="diaContentWork">
        <div class="taskName">
          <div class="name">案例名称</div>
          <div class="value">
            <el-input v-model="dataItem.title" placeholder="请输入案例名称(2-10个字符)"></el-input>
          </div>
        </div>
        <div class="ourLogo">
          <div class="name">品牌logo</div>
          <div class="value">
            <div class="uploadInfo">
              <div class="left">
                <el-upload
                  class="avatar-uploader"
                  action="#"
                  :show-file-list="false"
                  :multiple="false"
                  accept="image/png, image/jpeg"
                  :before-upload="(file) => handleFileChange(file, 'logo')"
                >
                  <i
                    v-if="dataItem.logo"
                    class="el-icon-delete avatar-uploader-icon"
                    @click.stop="() => handleDeleteFile('logo') "
                  ></i>
                  <img v-if="dataItem.logo" :src="dataItem.logo" class="avatar" />
                  <div v-else class="noneImage">
                    <i class="el-icon-plus avatar-uploader-icon"></i>
                  </div>
                </el-upload>
              </div>
              <div class="right">
                <p>（800*800，图片最大2M，最多1张）</p>
              </div>
            </div>
          </div>
        </div>
        <div class="taskFile">
          <div class="name">案例附件</div>
          <div class="value">
            <el-upload
              class="upload-demo"
              action="#"
              :show-file-list="true"
              :multiple="false"
              accept="application/pdf"
              :file-list="fileList"
              :before-upload="handlePDFFileChange"
              :before-remove="handlePDFFileRemove"
            >
              <div style="margin-top: 10px">
                <span class="uploadFileWord">立即上传</span>
                <span class="uploadFileTip">仅支持PDF格式(最大2M)</span>
              </div>
            </el-upload>
          </div>
        </div>
        <div class="taskDesc">
          <div class="name">案例描述</div>
          <div class="value">
            <editor
              :content="dataItem.description"
              @change="(val) => dataItem.description = val"
              :haveVideo="true"
              placeholder="支持图文混排，请至少添加不低于100字成功案例描述"
            ></editor>
          </div>
        </div>
      </div>
      <div class="dialog-footer">
        <div class="submit" @click="addCase">
          <p>提交</p>
        </div>
        <div class="cancle" @click="qx">
          <p>取消</p>
        </div>
      </div>
  </div>
</template>

<script>
  import editor from "@/components/editor";
  import uploadFile from "@/mixins/uploadFile";
  import DealSeoFooter from "@/components/kaifain/dealSeoFooter";
  import KaifainFooter from "@/components/SeoFooter";

  export default {
    name: "userSetting",
    components: {
      editor,
      KaifainFooter,
    },
    props: {
      lastId: {
        type: Number,
        default: 0
      },
    },
    data() {
      return {
        data: {
          city: 1,
          industry: null, //所处行业的ID
          title: "", //服务名称
          description: "", //简单描述
          images: "", //封面图片，缩略图的地址URL
          detail: "", //具体的描述
          tech_type: null, //技术类型
          successful_case: [],
          status: 0,
        },
        tempData: {},
        industryList: [],
        techTypeList: [],
        dialogVisible: false,
        dataItem: {
          provider_id: 0, //服务商ID
          title: "", //成功案例1
          logo: "", //http://www.baidu.com，URL
          description: "", //描述一下啊啥的发啊的算法
          file: "", //https://www.baidu.com，用户上传的PDF，格式必须为PDF，URL
        },
        fileList: [],
        kaifainUrl: ""
      };
    },
    async asyncData({ ...params }) {
      try {
        params.store.commit("updateNoneCommonFooter", true);
      } catch (e) {
        console.log("updateNoneCommonFooter", e);
      }
      let dealSeoFooterObj = new DealSeoFooter(params);
      let footer = await dealSeoFooterObj.dealData();
      let domainConfig = params.store.state.domainConfig;
      return {
        ...domainConfig,
        ...footer,
        mobile: params.app.$deviceType.isMobile(),
      };
    },
    mixins: [uploadFile],
    computed: {
      statusObj() {
        let status = Number(this.data.status || 0);
        let nameList = ["未申请", "审核中", "已入驻", "拒绝"];
        let o = {
          isOk: status === 2,
          name: nameList[status],
        };
        return o;
      },
      isDis() {
        let status = Number(this.data.status || 0);
        return status === 1;
      },
    },
    created() {
      const {kaifainUrl, jishuBaseUrl, siteUrl} = this.$store.state.domainConfig;
      this.kaifainUrl = kaifainUrl
      this.siteUrl = siteUrl
    },
    async mounted() {
      this.needLogin();
      //如果存在ID,则优先获取ID
      if (this.lastId) {
        this.getLastDetail();
      } else {
        this.getDraftInfo();
      }
      this.getTypeList();
    },
    methods: {
      jumpTo() {
        location.href = this.siteUrl + "/otherpage/companyComplete";
      },
      /** 图片文件上传 **/
      handleFileChange(file, type) {
        const isJPG = file.type === "image/jpeg";
        const isPNG = file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG && !isPNG) {
          this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
          return;
        }
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
          return;
        }
        const formData = new FormData();
        formData.append("file", file);
        formData.append("original_filename", file.name);
        this.uploading = true;
        this.$axios
          .$post(`/upload_image`, formData, {
            headers: { "Content-Type": "multipart/form-data" },
          })
          .then((res) => {
            if (type === "images") {
              this.data.images = res.filename;
            } else if (type === "logo") {
              this.dataItem.logo = res.filename;
            }
            console.log("type", type, this.data, this.dataItem);
          })
          .finally(() => {
            this.uploading = false;
          });
      },
      /** 删除问及爱你 **/
      handleDeleteFile(type) {
        if (type === "images") {
          this.data.images = "";
        } else if (type === "logo") {
          this.dataItem.logo = "";
        }
      },
      /** pdf上传  **/
      handlePDFFileChange(file, type) {
        console.log(file);
        const isPDF = file.type === "application/pdf";
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isPDF) {
          this.$message.error("上传文件只能是 JPG/PNG 格式!");
          return;
        }
        // if (!isLt2M) {
        // this.$message.error('上传文件大小不能超过 2MB!');
        // return
        // }
        const formData = new FormData();
        formData.append("file", file);
        formData.append("original_filename", file.name);
        this.uploading = true;
        this.apiPrepareUpload(file, (res) => {
          if (res.data && res.data.status === 1) {
            let url = res.data.data.url;
            this.dataItem.file = url;
            this.fileList = [{ name: file.name, url: url }];
          } else {
            this.$message.error("上传失败");
          }
        });
        return false;
      },
      /** pdf删除 **/
      handlePDFFileRemove() {
        this.fileList = [];
        this.dataItem.file = "";
      },
      /** 弹窗逻辑 **/
      submitChange() {},
      /** 获取选择信息 **/
      getTypeList() {
        this.$axios.get("/api/kaifawu/get_options").then((res) => {
          if (Number(res.data.status) === 1) {
            this.industryList = res.data.data.industries;
            this.techTypeList = res.data.data.tech_types;
          }
        });
      },
      /** 点击添加生成案例 **/
      async addSuccessInfo() {
        let res = null;
        if (!this.data.id) {
          res = await this.saveDraft();
        }
        if (this.data.id || res) {
          this.dialogVisible = true;
          this.dataItem = {
            provider_id: "", //服务商ID
            title: "", //成功案例1
            logo: "", //http://www.baidu.com，URL
            description: "", //描述一下啊啥的发啊的算法
            file: "", //https://www.baidu.com，用户上传的PDF，格式必须为PDF，URL
          };
        }
      },
      /** 删除案例 **/
      deleteCase(item) {
        this.$confirm("此操作将直接删除该成功案例, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$axios
              .post("/api/kaifawu/delete_case", {
                id: item.id,
              })
              .then((res) => {
                if (Number(res.data.status) === 1) {
                  this.$message({
                    type: "success",
                    message: "删除成功!",
                  });
                }
              });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      },
      /** 添加案例 **/
      async addCase() {
        let p = {};
        let keyList = [
          "id",
          "provider_id",
          "title",
          "logo",
          "description",
          "file",
        ];
        for (let key of keyList) {
          if (this.dataItem[key]) {
            p[key] = this.dataItem[key];
          }
        }
        p.provider_id = this.lastId;
        let isEdit = !!p.id;
        if (!p.title || p.title.length < 2 || p.title.length > 20) {
          this.$message.warning("请填写2-20字符的案例名称！");
          return;
        }
        if (!p.logo) {
          this.$message.warning("请上传品牌logo");
          return;
        }
        if (!p.description || p.description.length < 100) {
          this.$message.warning("请填写100字符的案例描述");
          return;
        }
        // if (!p.file) {
        //   this.$message.warning('请上传案例附件')
        //   return
        // }
        let url = isEdit ? "/api/kaifawu/update_case" : "/api/kaifawu/store_case";
        this.$axios.post(url, p).then((res) => {
          if (Number(res.data.status) === 1) {
            this.$emit('getLastDetail');
            this.$message.success(isEdit ? "更新成功" : "添加成功");
          }
        });
      },
      qx()
      {
        this.$emit('getLastDetail');
      },
      openEditCase(item) {
        this.dataItem = {
          ...item,
        };
        if (item.file) {
          this.fileList = [
            {
              name: "成功案例.pdf",
              url: item.file,
            },
          ];
        } else {
          this.fileList = [];
        }

        this.dialogVisible = true;
        console.log("openEditCase", this);
      },
      /** 获取草稿 **/
      getDraftInfo(isPreview) {
        this.$axios.get("/api/kaifawu/get_draft").then((res) => {
          if (Number(res.data.status) == 1 && res.data.data) {
            let data = res.data.data;
            if (!Array.isArray(data.successful_case)) {
              if (
                data.successful_case &&
                typeof data.successful_case === "object"
              ) {
                data.successful_case = [data.successful_case];
              } else {
                data.successful_case = [];
              }
            }

            data.city = Number(data.city);
            data.industry = Number(data.industry);
            data.tech_type = Number(data.tech_type);
            this.data = data;
          }
        });
      },
      /** 传入id后处理 **/
      getLastDetail() {
        this.$axios
          .post("/api/kaifawu/get_provider", {
            id: this.lastId,
            self: 1,
          })
          .then((res) => {
            if (Number(res.data.status) === 1) {
              let data = res.data.data;
              data.city = Number(data.city);
              data.industry = Number(data.industry);
              data.tech_type = Number(data.tech_type);
              if (!Array.isArray(data.successful_case)) {
                if (
                  data.successful_case &&
                  typeof data.successful_case === "object"
                ) {
                  data.successful_case = [data.successful_case];
                } else {
                  data.successful_case = [];
                }
              }
              this.data = data;
            }
          });
      },

      /** 存储草稿 **/
      async saveDraft(isPublish, isPreview) {
        let url = "/api/kaifawu/store";
        if (this.data.id) {
          url = "/api/kaifawu/publish";
        }
        let p = {
          ...this.data,
          publish: isPublish ? 1 : 0,
        };
        //服务名称
        if (!p.title) {
          this.$message.warning("请填写正确的服务名称（2-20字符）");
          return;
        }
        //所处行业
        if (!p.industry) {
          this.$message.warning("请选择所处行业");
          return;
        }
        //技术类型
        if (!p.tech_type) {
          this.$message.warning("请选择技术类型");
          return;
        }
        //缩略图
        if (!p.images) {
          this.$message.warning("请上传缩略图");
          return;
        }
        //方案简介
        if (
          !p.description ||
          p.description.length < 8 ||
          p.description.length > 255
        ) {
          this.$message.warning("请填写正确的方案简介（8-255字符）");
          return;
        }
        //方案简介
        if (!p.detail) {
          this.$message.warning("请填写方案介绍");
          return;
        }
        // 更改已有的时候发布，校验状态
        if (p.publish === 1 && this.lastId && Number(this.data.status) === 2) {
          this.$message.warning("该解决方案已发布，暂不允许修改");
          return;
        }
        let res = await this.$axios.post(url, p);
        if (Number(res.data.status) === 1) {
          if (!isPublish) {
            this.getDraftInfo(isPreview);
            this.$message.success("保存草稿成功");
          } else {
            this.$message.success("提交成功");
            this.$emit('service_provider');
          }
          return true;
        }
      },
      /** 确认提交 **/
      submitAll() {
        this.saveDraft(true);
      },
      /** 预览 **/
      preview() {
        try {
          localStorage.setItem("kaifainPreviewData", JSON.stringify(this.data));
          window.open(`/kaifain/preview`, "_black");
        } catch (e) {
          console.log("");
        }
      },
      /** 预览 **/
      previewCase() {
        try {
          localStorage.setItem(
            "kaifainPreviewCaseData",
            JSON.stringify(this.dataItem)
          );
          window.open(`${this.kaifainUrl}/previewCase`, '_black')
        } catch (e) {
          console.log("");
        }
      },
      openNewUrl(item) {
        window.open(item.file, "__black");
      },
      jumpToOther() {
        let url = "https://kaifain.proginn.com/s/10";
        window.open(url, "__black");
      },
    },
  };
</script>
<style lang="scss" scoped>
  @import "../../assets/css/kaifain/kaifainAdd.scss";
</style>
<style lang="scss">
  @import "../../assets/css/kaifain/kaifainAddNoScoped.scss";
</style>
