<template>
  <section class="Add">
    <ai-detail>
      <ai-title slot="title" :title="addTitle" isShowBottomBorder isShowBack @onBackClick="back"/>
      <template #content>
        <el-form :model="form" ref="ruleForm" :rules="rules" label-width="130px" label-position="right" size="small">
          <ai-card title="基本信息">
            <template #content>
              <el-form-item label="标题" prop="title">
                <el-input v-model="form.title" placeholder="请输入标题" :maxlength="50" show-word-limit/>
              </el-form-item>
              <el-form-item label="发布地区" prop="areaId">
                <ai-area-get :instance="instance" v-model="form.areaId" :root="rootArea" />
              </el-form-item>
              <el-form-item label="文章类型" prop="moduleId" style="width:50%;" v-if="miniTypeList.length">
                <ai-select v-model="form.moduleId" :selectList="miniTypeList" @change="getNewTypeList"/>
              </el-form-item>
              <el-form-item label="分类" prop="categoryId"  style="width:50%;">
                <ai-select v-model="form.categoryId" :selectList="newTypeList"/>
              </el-form-item>
              <el-form-item label="正文" prop="content" style="width: 100%;">
                <ai-editor v-model="form.content" :instance="instance"/>
              </el-form-item>
              <el-form-item label="封面图片" >
                <ai-uploader
                  :isShowTip="true"
                  :instance="instance"
                  v-model="form.pictureUrlList"
                  fileType="img"
                  acceptType=".png,.jpg,.jpeg"
                  :limit="1">
                  <template slot="tips">最多上传1张图片,单张图片最大10MB<br/>支持.png,.jpg,.jpeg格式</template>
                </ai-uploader>
              </el-form-item>
              <el-form-item label="附件附件" prop="files">
                <el-upload
                    class="upload-demo"
                    action
                    multiple
                    accept=".zip,.rar,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.txt,.jpg,.png"
                    :http-request="uploadFile"
                    :on-exceed="()=>$message.error('最多只能上传9个附件!')"
                    :on-remove="handleRemove"
                    :on-change="handleChange"
                    :limit="9"
                    :file-list="form.files">
                  <el-button size="mini"> 添加附件</el-button>
                  <div slot="tip" class="el-upload__tip">
                    <p style="line-height: 0;">最多上传9个附件,单个文件最大10MB </p>
                    <p style="line-height: 40px;">
                      支持.zip、.rar、.doc、.docx、.xls、.xlsx、.ppt、.pptx、.pdf、.txt、.jpg、.png格式</p>
                  </div>
                </el-upload>
              </el-form-item>
            </template>
          </ai-card>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="back">取消</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </template>
    </ai-detail>
  </section>
</template>

<script>

import {mapState} from "vuex";

export default {
  name: "Add",
  props: {
    instance: Function,
    dict: Object,
    permissions: Function
  },
  computed: {
    ...mapState(['user']),
    isEdit() {
      return !!this.$route.query.id
    },
    addTitle() {
      return this.isEdit ? "编辑新闻发布" : "添加新闻发布"
    },
    rules() {
      return {
        title: [{required: true, message: "请输入标题"}],
        areaId: [
          {message: "请选择发布地区", required: true, trigger: "blur"},
          {validator: (r, v, cb) => v && /0{3}$/g.test(v) ? cb('发布地区必须选到村级') : cb(), trigger: "blur"}
        ],
        moduleId: [{required: true, message: "请选择文章类型"}],
        categoryId: [{required: true, message: "选择分类"}],
        content: [{required: true, message: "请输入正文"}],
      }
    },
    rootArea() {
      return this.user.info?.areaId?.replace(/(\d{6})\d+/g, '$1' + Array(7).join("0")) || ""
    }
  },
  data() {
    return {
      form: {
        pictureUrlList: [],
        pictureUrl: '',
        files: []
      },
      miniTypeList: [],
      newTypeList: [],
    }
  },
  methods: {
    // 上传附件
    uploadFile: function (file) {
      const isLt10M = file.file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error("附件大小不超过10mb!");
        for (let i = 0; i < this.form.files.length; i++) {
          if (this.form.files[i].uid == file.file.uid) {
            this.form.files.splice(i, 1);
          }
        }
        return;
      }
      let formData = new FormData();
      formData.append("file", file.file);
      this.instance.post(`/admin/file/add`, formData, {withCredentials: false}).then(res => {
        if (res && res.code == 0) {
          let img = res.data[0].split(';');
          this.form.files.forEach((item, index) => {
            if (item.uid == file.file.uid) {
              this.form.files[index].id = img[1];
            }
          })
        }
      });
    },
    handleRemove(file, fileList) {
      this.form.files = fileList;
    },
    handleChange(file, fileList) {
      this.form.files = fileList;
    },
    back() {
      this.$router.push({})
    },
    submit() {
      this.$refs.ruleForm.validate(v => {
        if (v) {
          if(this.form.pictureUrlList && this.form.pictureUrlList.length) {
            this.form.pictureUrl = this.form.pictureUrlList[0].url
          }
          this.instance.post(`/app/apppublicityinfo/addOrUpdate`, this.form).then(res => {
            if (res.code == 0) {
              this.$message.success('提交成功!');
              this.back()
            }
          })
        }
      })
    },
    getDetail() {
      let {id} = this.$route.query
      id && this.instance.post("/app/apppublicityinfo/queryDetailById", null, {
        params: {id}
      }).then(res => {
        if (res?.data) {
          res.data.pictureUrlList = []
          if(res.data.pictureUrl) {
            res.data.pictureUrlList = [{url: res.data.pictureUrl}]
          }
          this.form = {...res.data}
          this.getNewTypeList()
        }
      })
    },
    getTypeList() {
      let {parentId} = this.$route.query
      this.instance.post(`/app/apppublicitycategory/list?categoryType=1&size=100&parentId=${parentId}`).then(res => {
        if (res.code == 0) {
          this.miniTypeList = res.data.records.map((item) => {
            return {
              dictName: item.categoryName,
              dictValue: item.id
            }
          })
          console.log(this.miniTypeList)
          if(this.$route.query.id) {
            this.getDetail()
          }
        }
      })
    },
    getNewTypeList() {
      this.instance.post(`/app/apppublicitycategory/list?categoryType=2&size=100&parentId=${this.form.moduleId}`).then(res => {
        if (res.code == 0) {
          res.data.records
          this.newTypeList = res.data.records.map((item) => {
            return {
              dictName: item.categoryName,
              dictValue: item.id
            }
          })
        }
      })
    },
  },
  created() {
    this.getTypeList()
  }
}
</script>

<style lang="scss" scoped>
.Add {
  height: 100%;

  .half {
    align-items: flex-start;

    & > .el-form-item, & > div {
      width: 50%;

      .el-form-item {
        width: 100%;
      }
    }
  }

  .el-date-editor {
    width: 100%;
  }
}
</style>
