<template>
  <section class="replyDetail">
    <u-form :model="form" ref="replyForm" :rules="rules">
      <u-form-item label="分类" prop="category" required>
        <ai-select :value="form.category" :list="categories" @data="v=>form.category=v[0].value"/>
      </u-form-item>
      <u-form-item label="标题">
        <u-input class="textRight" v-model="form.title" placeholder="选填，仅内部可见" maxlength="30"/>
      </u-form-item>
      <u-form-item label="快捷回复类型" label-position="top" prop="contentType" required>
        <ai-tabs wrap plain :ops="types" v-model="form.contentType" @change="$refs.replyForm.setRules(rules)"/>
      </u-form-item>
      <u-form-item v-if="form.contentType=='text'" label="内容" label-position="top" prop="content" required>
        <ai-textarea v-model="form.content" maxlength="1000" placeholder="限1000字">
          <template #bar>
            <div class="textareaBtn" @tap="handleInsert(custom.name)">插入用户昵称</div>
            <!--            <div class="textareaBtn" @tap="handleInsert(custom.name)">插入备注名</div>-->
          </template>
        </ai-textarea>
      </u-form-item>
      <u-form-item v-else-if="['image','video','file','voice'].includes(form.contentType)"
                   :label="currentContentType.name"
                   label-position="top" prop="mediaId" required>
        <ai-uploader :type="form.contentType" :mediaId.sync="form.mediaId" :fileId.sync="form.fileId"
                     :placeholder="`添加${currentContentType.name}`" :def="form.file"/>
      </u-form-item>
      <template v-else-if="['news'].includes(form.contentType)">
        <u-form-item label="链接地址" label-position="top" prop="accessUrl" required>
          <u-input v-model="form.accessUrl" placeholder="链接地址请以http或https开头"/>
        </u-form-item>
        <u-form-item label="标题" prop="accessTitle" required>
          <u-input class="textRight" v-model="form.accessTitle" maxlength="50" placeholder="请输入链接标题"/>
        </u-form-item>
      </template>
      <template v-else-if="['miniprogram'].includes(form.contentType)">
        <u-form-item label="AppId" prop="accessAppid" required>
          <u-input class="textRight" v-model="form.accessAppid" placeholder="请输入小程序Appid"/>
        </u-form-item>
        <u-form-item label="页面路径" prop="accessUrl" required label-width="140">
          <u-input class="textRight" v-model="form.accessUrl" placeholder="请输入小程序页面路径"/>
        </u-form-item>
        <u-form-item label="标题" prop="accessTitle" required>
          <u-input class="textRight" v-model="form.accessTitle" maxlength="50" placeholder="请输入链接标题"/>
        </u-form-item>
      </template>
    </u-form>
    <div bottom>
      <u-button @tap="back">取消</u-button>
      <u-button type="primary" @tap="submitReply">保存</u-button>
    </div>
  </section>
</template>

<script>
import AiSelect from "../../components/AiSelect";
import AiTabs from "../../components/AiTabs";
import AiTextarea from "../../components/AiTextarea";
import AiUploader from "../../components/AiUploader";
import {mapActions} from "vuex";

export default {
  name: "replyDetail",
  components: {AiUploader, AiTextarea, AiTabs, AiSelect},
  computed: {
    types() {
      return [
        {name: "文字", value: "text"},
        {name: "图片", value: "image"},
        {name: "视频", value: "video"},
        {name: "附件", value: "file"},
        {name: "链接", value: "news"},
        {name: "小程序", value: "miniprogram"},
      ]
    },
    currentContentType() {
      return this.types.find(e => e.value == this.form.contentType) || {}
    },
    rules() {
      return {
        category: [{required: true, message: "请选择分类"}],
        contentType: [{required: true, message: "请选择快捷回复类型"}],
        content: [{required: true, message: "请填写内容"}],
        accessUrl: [{required: true, message: "请填写链接地址"}],
        accessAppid: [{required: true, message: "请填写小程序AppId"}],
        accessTitle: [{required: true, message: "请填写标题"}],
        mediaId: [{required: true, message: `请上传${this.currentContentType.name}`}],
      }
    }
  },
  data() {
    return {
      form: {contentType: "text"},
      categories: [],
      type: "",
      custom: {}
    }
  },
  methods: {
    ...mapActions(['injectJWeixin', 'wxInvoke']),
    back() {
      uni.redirectTo({url: "./quickReply"})
    },
    getCategories() {
      this.$http.post("/app/wxcp/wxspeechtechniquecategory/listAll", null, {
        params: {type: this.type}
      }).then(res => {
        if (res?.data) {
          this.categories = res.data.map(e => ({label: e.name, value: e.id}))
        }
      })
    },
    getDetail(id) {
      this.$http.post("/app/wxcp/wxspeechtechnique/list", null, {
        params: {id}
      }).then(res => {
        if (res?.data) {
          this.form = res.data.records?.[0]
        }
      })
    },
    submitReply() {
      this.$refs.replyForm.validate(v => {
        if (v) {
          this.$http.post("/app/wxcp/wxspeechtechnique/addOrUpdate", {...this.form, type: this.type}).then(res => {
            if (res?.code == 0) {
              this.$u.toast("提交成功!")
              uni.navigateTo({url: './quickReply'})
            }
          })
        }
      })
    },
    getCustom() {
      this.wxInvoke(['getCurExternalContact', {}, res => {
        if (res?.err_msg == 'getCurExternalContact:ok') {
          this.$http.post("/app/wxcp/wxcustomer/queryCustomerById", null, {
            params: {id: res.userId}
          }).then(ret => {
            if (ret?.data) {
              this.custom = ret.data
            }
          })
        }
      }])
    },
    handleInsert(str) {
      if (str) {
        this.form.content = (this.form.content || "") + str
        this.$forceUpdate()
      }
    }
  },
  created() {
    this.injectJWeixin("getCurExternalContact").then(() => this.getCustom())
    let {type, id} = this.$route.query
    this.type = type
    this.getCategories()
    id && this.getDetail(id)
  },
  mounted() {
    this.$nextTick(() => this.$refs.replyForm.setRules(this.rules))
  }
}
</script>

<style lang="scss" scoped>
.replyDetail {
  border-top: 1px solid #D4D4D4;
  padding: 16px 0 208px;
  background: #F5F5F5;
  box-sizing: border-box;

  ::v-deep .u-form-item {

    .u-form-item--left {
      margin-bottom: 0 !important;
    }

    .u-form-item--right__content__slot {
      justify-content: flex-end;
    }

    & + .u-form-item {
      margin-top: 16px;
    }

    .textRight {
      .uni-input-wrapper {
        text-align: right;
      }
    }
  }

  .textareaBtn {
    font-size: 26px;
    color: #1365DD;
  }
}
</style>
