<template>
  <el-main class="bg_white" style="min-height: calc( 100% - 80px )">
    <el-row class="title_box">
      <el-col :span="24"><div class="title">说明书管理</div></el-col>
    </el-row>
    <div class="form_box">
      <el-form :model="data.formData" ref="ruleForms" :rules="data.rules" label-width="120px" label-position="left">
        <el-form-item label="说明书名称：" prop="name">
          <el-input v-model="data.formData.name" />
        </el-form-item>
        <el-form-item label="说明书标签：" prop="tags" >
          <el-input v-model="data.formData.tags"/>
        </el-form-item>
        <el-form-item label="说明书描述：" prop="description">
          <el-input
            v-model="data.formData.description"
            :rows="3"
            type="textarea"
            placeholder="说明书描述"
          />
        </el-form-item>
        <el-form-item label="封面图：" prop="">
          <el-upload
            ref="upload"
            :action="data.api_upload_url"
            v-model:file-list="data.formData.show_img"
            list-type="picture-card"
            :with-credentials="true"
            name="image"
            :data="data.extra"
            :on-success="function (res, file, file_list) {return handleSuccess(res, file, file_list, data.formData)}"
            :on-preview="handlePreview"
            :limit="1"
            :on-remove="handleRemove"
            accept=".jpg,.png"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="适配型号：" prop="product_sn">
          <el-input v-model="data.formData.product_sn" />
        </el-form-item>
        <el-form-item label="驱动上传：" prop="url">
          <m-chunk-upload :chunk-size="1" :request-limit="4" @successed="completeInfoUpload($event, { index: '-1' })"
            @upload-progress="progress" @hash-progress="hash">
            <span class="opd-btn opd-btntype3">上传文件</span>
          </m-chunk-upload>
          <div class="drive_url m-l-20" v-if="data.formData.url">{{data.formData.url}}
            <i class="el-icon-circle-close" style="margin-left:5px;" @click="close" ></i>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="bottom_box">
      <div class="text-r">
        <el-button type="primary" @click="addClick">确定</el-button>
      </div>
    </div>
    <!--图片放大弹窗-->
    <el-dialog v-model="data.dialogVisible">
      <el-image width="100%" :src="data.dialogImg" alt></el-image>
    </el-dialog>
  </el-main>
</template>
<script>
import { reactive, onMounted, onActivated, ref } from 'vue'
import { useRoute, onBeforeRouteUpdate } from 'vue-router'
import Request from '@/utils/request.js'
import { ElMessage } from 'element-plus'
import { useStore } from 'vuex'
import MChunkUpload from '@/components/m-chunk-upload.vue'
export default {
  name: 'EditInstruct',
  components: {
    'm-chunk-upload': MChunkUpload
  },
  setup() {
    const data = reactive({
      cdn: '',
      api_upload_url: process.env.VUE_APP_API_BASEURL + "admin/v1/manual/upload",
      extra: {
        type: 'images',
        language_id: 1
      },
      dialogVisible: false,
      dialogImg: '',
      id: '',
      language_id: 0,
      type: '',
      formData: {
        description: "",
        id: 0,
        image: "",
        language_id: 0,
        name: "",
        product_sn: "",
        tags: "",
        url: "",
        show_img: [],
        show_file: []
      },
      rules: {
        name: [
          { required: true, message: "名称不能为空!", trigger: "blur" },
        ],
        product_sn: [
          { required: true, message: "适配型号不能为空!", trigger: "blur" }
        ],
        url: [
          { required: true, message: "驱动不能为空!", trigger: "blur" }
        ]
      },
      addParams: {
        id: '',
        description: "",
        image: "",
        language_id: 0,
        name: "",
        product_sn: "",
        tags: "",
        url: "",
      }
    })
    const ruleForms = ref(null)
    let route = useRoute()
    let store =  useStore()
    const request = new Request()

    onMounted(() => {})
    onActivated(() => {
      data.language_id = store.state.user.language.id
      data.extra.language_id = store.state.user.language.id
      data.id = route.query.id
      data.type = route.query.type
      data.cdn = store.state.user.cdn
      //处理标签名称
      let tags = store.state.topNavTag.tags
      let cur_path = route.path
      let cur_id = route.query.id
      tags.forEach(item => {
        if (item.path == cur_path && item.query.id == cur_id) {
          if (data.type == 'add') {
            item.meta.title = '新增说明书'
          } else {
            item.meta.title = '编辑说明书'
          }
        }
      })
      getDetails()
    })
    //监听路由变化
    onBeforeRouteUpdate((to) => {
      data.id = to.query.id
      data.type = to.query.type
      //处理标签名称
      let tags = store.state.topNavTag.tags
      let cur_path = to.path
      let cur_id = to.query.id
      tags.forEach(item => {
        if (item.path == cur_path && item.query.id == cur_id) {
          if (data.type == 'add') {
            item.meta.title = '新增说明书'
          } else {
            item.meta.title = '编辑说明书'
          }
        }
      })
      getDetails()
    })
    //清空数据
    const clearData = () => {
      data.formData = {
        description: "",
        id: 0,
        image: "",
        language_id: 0,
        name: "",
        product_sn: "",
        tags: "",
        url: "",
        show_img: [],
        show_file: []
      }
    }
    const getDetails = () => {
      if (data.type == 'add') {
        clearData()
        return false;
      }
      if (data.type == 'edit') {
        request.get('v1/manual/' + data.id,{id: data.id}).then(res=>{
          if(res.status == 200){
            data.formData = res.data
            let url = res.data.url
            data.formData.url = url.substring(url.lastIndexOf("/")+1)
            data.addParams.image = data.formData.image
            data.addParams.url = data.formData.url
            data.formData.show_img = [
              {
                uid: data.formData.id,
                url: data.cdn + data.formData.image
              }
            ]
            data.formData.show_file = [
              {
                uid: data.formData.id,
                url: data.cdn + data.formData.url
              }
            ]
          }else {
            ElMessage({
              type: 'error',
              message: res.message
            })
          }
        })
      }
    }
    const handlePreview = (file) => {
      data.dialogImg = file.url
      data.dialogVisible = true
    }
    const handleSuccess = (res, file, fileList, item) => {
      console.log(res, file, item)
      data.addParams.image = res.data[0].r_path
      data.formData.show_img = [{
        uid: file.uid,
        url: res.data[0].url
      }]
    }
    const handleRemove = () => {}
    //驱动上传
    const completeInfoUpload = (f, d) => {
      console.log(f,d)
      let files = f.data[0]
      if (files.url) {
        data.addParams.url = files.r_path
        data.formData.show_file = [{
          uid: files.md5,
          url: files.url
        }] 
        data.formData.url = files.file
      }
    }
    const close = () => {
      data.formData.url = ''
    }

    //新增/编辑
    const addClick = () => {
      data.addParams.language_id = data.language_id
      data.addParams.name = data.formData.name
      data.addParams.description = data.formData.description
      data.addParams.tags = data.formData.tags
      data.addParams.product_sn = data.formData.product_sn
      ruleForms.value.validate((valid) => {
        if (valid == false) {
          ElMessage({
            type: 'error',
            message: '请填写完整您要提交的内容！'
          })
          return false;
        } else {
          if (data.type == 'edit') {
            data.addParams.id = data.id
            request.put('v1/manual/'+ data.id, data.addParams).then(res=>{
              if(res.status == 200){
                ElMessage({
                  type: 'success',
                  message: res.message
                })
              } else {
                ElMessage({
                  type: 'error',
                  message: res.message
                })
              }
            })
          } else {
            data.addParams.id = ''
            request.post('v1/manual', data.addParams).then(res=>{
              if(res.status == 200){
                ElMessage({
                  type: 'success',
                  message: res.message
                })
              } else {
                ElMessage({
                  type: 'error',
                  message: res.message
                })
              }
            })
          }
        }
      })
    }

    return {
      data,
      ruleForms,
      getDetails,
      handlePreview,
      handleSuccess,
      handleRemove,
      addClick,
      completeInfoUpload,
      close,
      clearData
    }
  }
}
</script>
<style scoped>
::v-deep(.el-upload){
  position: relative;
}
.el-icon-plus{
  position: absolute;
  width: 28px;
  height: 28px;
  top: calc( 50% - 14px );
  left: calc( 50% - 14px );
}
.form_box ::v-deep(.el-input), .form_box ::v-deep(.el-textarea) {
    width: 45%;
}
.form_box ::v-deep(.el-upload--picture-card),
::v-deep(.el-upload-list--picture-card .el-upload-list__item),
::v-deep(.el-upload-list--picture-card .el-upload-list__item-actions){
  width: 120px !important;
  height: 120px !important;
}
::v-deep(.el-upload-list--picture-card){
  --el-upload-list-picture-card-size: 120px;
}
.form_box{
  margin: 24px 24px 0 24px;
  padding-bottom: 80px;
}
.form_box form{
  padding: 0 10px;
}
.bottom_box{
  padding: 16px;
  width: calc( 100vw - 32px );
}
</style>