<template>
  <ai-detail class="addRural">
    <template slot="title">
      <ai-title :title="detailTitle" isShowBack :isShowBottomBorder="true" @onBackClick="$emit('goto')"></ai-title>
    </template>
    <template #content>
      <ai-card title="基本信息">
        <template #content>
          <el-form :model="ruleForm" label-width="120px" ref="ruleForm" :rules="rules" style="padding-top:16px;">
            <el-form-item label="标题" prop="title">
              <el-input type="textarea" :rows="2" v-model="ruleForm.title" clearable placeholder="请输入..." maxlength="30"
                        show-word-limit></el-input>
            </el-form-item>
            <el-form-item prop="areaId" label="发布地区">
              <ai-area-select clearable always-show :instance="instance"
                              v-model="ruleForm.areaId"
                              :disabled-level="disabledLevel">
              </ai-area-select>
            </el-form-item>
            <el-form-item label="正文" prop="content">
              <!-- <vue-ueditor-wrap v-model="ruleForm.content" :config="$ueditor_config" maxLength="3000"></vue-ueditor-wrap> -->
              <ai-editor v-model="ruleForm.content" :instance="instance"/>
            </el-form-item>
            <el-form-item label="缩略图" prop="thumbUrl">
              <ai-uploader
                  :instance="instance"
                  isShowTip
                  v-model="ruleForm.thumbUrl"
                  :limit="1"
                  :cropOps="cropOps"
                  is-crop>
                <template slot="tips">
                  <p>最多上传1张图片,单个文件最大10MB，支持jpg、jpeg、png格式</p>
                  <p>图片比例：1.6：1</p>
                </template>
              </ai-uploader>
            </el-form-item>
            <el-form-item label="图片信息" v-if="detailTitle == '旅游服务'">
              <span class="upload-more" style="left:-70px">(最多9张)</span>
              <ai-uploader
                  :instance="instance"
                  v-model="fileList"
                  :limit="9">
              </ai-uploader>
            </el-form-item>
          </el-form>
        </template>
      </ai-card>
    </template>
    <template #footer>
      <template v-if="!isEdit">
        <el-button size="small" style="width: 92px;" @click="$emit('goto')">取消</el-button>
        <el-button type="primary" size="small" style="width: 92px;" @click="confirm('ruleForm', '0')">保存</el-button>
        <el-button type="primary" size="small" style="width: 92px;" @click="confirm('ruleForm', '1')">保存并发布</el-button>
      </template>
      <template v-if="isEdit && ruleForm.status != '1'">
        <el-button size="small" style="width: 92px;" @click="$emit('goto')">取消</el-button>
        <el-button type="primary" size="small" style="width: 92px;" @click="confirm('ruleForm', '0')">修改</el-button>
        <el-button type="primary" size="small" style="width: 92px;" @click="confirm('ruleForm', '1')">修改并发布</el-button>
      </template>
      <template v-if="isEdit && ruleForm.status  == '1'">
        <el-button size="small" style="width: 92px;" @click="$emit('goto')">取消</el-button>
        <el-button type="primary" size="small" style="width: 92px;" @click="confirm('ruleForm', '1')">修改</el-button>
      </template>
    </template>
  </ai-detail>
  <!-- <div class="addRural detail-content details-page no-content-border">
    <el-row type="flex" style="position: relative;height: calc(100% - 112px);">
      <div class="right-content">
        <div :style=" isEdit ? 'width: 790px;margin: 0 auto;position:relative;' : 'width: 790px;margin: 0 auto;position:relative;padding-bottom: 80px;' ">
          <el-form :model="ruleForm" label-width="120px" ref="ruleForm" :rules="rules" style="padding-top:16px;">
            <el-form-item label="标题" prop="title">
              <el-input size="small" v-model="ruleForm.title" clearable placeholder="请输入..." style="width: 240px;" maxLength="20"></el-input>
            </el-form-item>
            <el-form-item prop="areaId" label="发布地区">
              <ai-area-select clearable always-show :instance="instance"
                v-model="ruleForm.areaId"
                :disabled-level="disabledLevel">
              </ai-area-select>
            </el-form-item>
            <el-form-item label="正文" prop="content">
              <ai-editor  v-model="ruleForm.content" :instance="instance" />
            </el-form-item>
            <el-form-item label="缩略图" prop="thumbUrl">
                <ai-uploader
                  :instance="instance"
                  v-model="ruleForm.thumbUrl"
                  :limit="1"
                  :cropOps="cropOps"
                  is-crop>
                  <template slot="tips">图片比例：1.6：1</template>
                </ai-uploader>
            </el-form-item>
            <el-form-item label="图片信息" v-if="detailTitle == '旅游服务'">
              <span class="upload-more" style="left:-70px">(最多9张)</span>
              <el-upload
                  class="upload-demo upload-list"
                  ref="upload"
                  multiple
                  action
                  list-type="picture-card"
                  :file-list="fileList"
                  :http-request="uploadFile"
                  :on-remove="handleRemoveFile"
                  :on-change="fileChange"
                  accept=".jpeg,.jpg,.png">
                  <div class="upload-img">
                      <div class="iconfont iconPhoto"></div>
                      <div class="upload-text">上传照片</div>
                  </div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-row>
  </div> -->
</template>

<script>
import {mapState} from 'vuex';

export default {
  name: 'add-rural',
  props: {
    instance: Function,
    dict: Object,
    permissions: Function,
    detailTitle: String,
    isEdit: Boolean,
    areaId: String,
    type: String,
    detailId: String,
    disabledLevel: Number
  },
  data() {
    return {
      ruleForm: {
        title: '',
        content: '',
        areaId: '',
        createUnitName: '',
        createUserName: '',
        status: '',
        thumbUrl: []
      },
      cropOps: {
        width: "336px",
        height: "210px"
      },
      rules: {
        title: [
          {required: true, message: '请输入标题', trigger: 'change'}
        ],
        content: [
          {required: true, message: '请输入内容', trigger: 'change'}
        ],
        areaId: [
          // {required: true, validator: transferInAreaIdPass, trigger: 'change'}
          {required: true, message: '请选择发布地区', trigger: 'change'}
        ],
        photo: [
          {required: true, message: '请上传图片', trigger: 'blur'}
        ],
      },
      fileList: []
    };
  },
  filters: {
    timeVal(val) {
      if (val) {
        return val.substring(0, 10);
      }
    }
  },
  methods: {
    // 上传照片
    uploadFile(file) {
      var isPng = true
      isPng = file.file.type == 'image/jpeg' || file.file.type == 'image/png' || file.file.type == 'image/jpg';


      if (!isPng) {
        this.$message.warning('上传图片信息必须是jpeg/png/jpg格式!');
        for (let i = 0; i < this.fileList.length; i++) {
          if (this.fileList[i].uid == file.file.uid) {
            this.fileList.splice(i, 1);
          }
        }
        return
      }
      const isLt10M = file.file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.warning("图片大小不能超过 10MB!");
        for (let i = 0; i < this.fileList.length; i++) {
          if (this.fileList[i].uid == file.file.uid) {
            this.fileList.splice(i, 1);
          }
        }
        return;
      }
      if (this.fileList.length > 9) {
        this.$message.error('图片信息不能超过9张')
        this.fileList.map((item, index) => {
          if (item.uid == file.file.uid) {
            this.fileList.splice(index, 1)
          }
          return this.fileList
        })
        return
      }
      let formData = new FormData();
      formData.append("file", file.file);
      this.instance.post(`/admin/file/add`, formData).then(res => {
        if (res.msg == "success") {
          this.$message({message: '图片上传成功', type: 'success'})
          let imgInfo = res.data[0].split(';');
          let img = {
            'fileId': imgInfo[1],
            'accessUrl': imgInfo[0]
          }
          this.fileList.map((item, index) => {
            if (item.uid == file.file.uid) {
              this.fileList[index].fileId = img.fileId
              this.fileList[index].accessUrl = img.accessUrl
              this.fileList[index].url = img.accessUrl
            }
            return this.fileList
          })
        }
      })
    },
    handleRemoveFile(file, fileList) {
      this.fileList = fileList
    },
    fileChange(file, fileList) {
      if (fileList.lenth == 9) {
        this.$message.error('图片信息不能超过9张')
        return
      }
      this.fileList = fileList
    },
    cancel() {
      this.$emit('goto');
    },
    confirm(formName, status) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.status = status
          this.confirmAjax();
        } else {
          return false;
        }
      });
    },
    confirmAjax() {
      this.ruleForm.photo = JSON.stringify(this.fileList)
      this.instance.post('/app/appcountrysidetourism/addOrUpdate', {
        ...this.ruleForm,
        thumbUrl: this.ruleForm.thumbUrl.length ? JSON.stringify([{
          url: this.ruleForm.thumbUrl[0].url
        }]) : ''
      }).then(res => {
        if (res && res.code == 0) {
          this.detailId ? this.$message.success('修改成功') : this.$message.success('添加成功');
          this.cancel();
        }
      });
    },
    getDetail() {
      this.instance.post(`/app/appcountrysidetourism/queryDetailById?id=${this.detailId}`).then(res => {
        if (res && res.code == 0) {
          this.ruleForm = {...res.data}
          this.ruleForm.thumbUrl = res.data.thumbUrl ? JSON.parse(res.data.thumbUrl) : []
          if (this.ruleForm.photo) {
            this.fileList = JSON.parse(this.ruleForm.photo)
          }
        }
      });
    },

    contentInput() {
      this.$refs.ruleForm.validateField('content')
    }
  },
  mounted() {
    if (this.detailId) {  //编辑
      this.getDetail()
    } else {  //新增
      this.ruleForm.areaId = this.areaId
      this.ruleForm.type = this.type
      this.ruleForm.createUnitName = this.user.info.unitName
      this.ruleForm.createUserName = this.user.info.name
    }
  },
  computed: {
    ...mapState(['user'])
  },
};
</script>

<style scoped lang="scss">
.cover {
  display: block;
  width: 300px;
  height: 140px;
  margin: 20px auto;
}

.addRural {
  ::v-deep .upload-list .el-upload-list--picture-card {
    .el-upload-list__item-actions {
      width: 84px !important;
      height: 84px !important;
    }
  }

  ::v-deep .upload-list .el-upload-list__item {
    margin-right: 16px;
  }

  ::v-deep .upload-list .el-upload-list__item, .el-upload-list__item {
    img {
      width: 84px !important;
      height: 84px !important;
      border-radius: 2px !important;
    }
  }

  .upload-list {
    padding-bottom: 100px;

    ::v-deep .el-upload-list__item {
      width: 84px !important;
      height: 84px !important;
      border-radius: 2px !important;
    }
  }

  .upload-img {
    width: 84px;
    height: 84px;
    background: rgba(245, 245, 245, 1);
    border-radius: 2px;
    border: 1px solid rgba(208, 212, 220, 1);

    .iconPhoto {
      margin-top: 20px;
      font-size: 32px;
      color: #8B9CB6;
    }
  }

  .upload-demo {
    // padding: 0 15px;
  }

  .upload-text {
    color: rgba(102, 102, 102, 1);
    font-size: 12px;
    height: 16px;
    line-height: 16px;
  }

  ::v-deep .upload-list .el-upload--picture-card {
    width: 84px !important;
    height: 84px !important;
    line-height: 30px !important;
    background: rgba(245, 245, 245, 1) !important;
    border-radius: 2px !important;
    border: none !important;
  }
}
</style>
