<template>
  <div class="content-main helpManagerAddPage" v-loading="detailLoading">
    <el-form ref="formData" :model="formData" :rules="rules" label-width="85px">
      <el-row :gutter="20">
        <el-col :span="8" :offset="4">
          <el-form-item label="系统模块:" prop="gnmk">
            <el-input
              v-model="formData.gnmk"
              placeholder="请输入"
              clearable
              :disabled="isShow"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="文档标题:" prop="wdbt">
            <el-input
              v-model="formData.wdbt"
              placeholder="请输入"
              clearable
              :disabled="isShow"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8" :offset="4">
          <el-form-item label="推荐读者:" prop="tjdzarr">
            <el-select
              style="width: 100%"
              v-model="formData.tjdzarr"
              :disabled="isShow"
              multiple
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in tjdzOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="编制日期:" v-if="isShow">
            <el-date-picker
              :disabled="isShow"
              style="width: 100%"
              v-model="formData.bzrq"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8" :offset="4">
          <el-form-item label="用户场景:" prop="checkList" class="yhcjStyle">
            <el-checkbox-group v-model="formData.checkList" :disabled="isShow">
              <el-checkbox label="1">管理端</el-checkbox>
              <el-checkbox label="2">企业端</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="16" :offset="4">
          <el-form-item label="手册附件:" class="marginBot10">
			  <div  v-if="isShow">
			  <el-row
			    v-for="(item, index) in fileList"
			    :key="index"
			  >
			   <!-- <span @click="viewFileFun(item.id)" style="cursor: pointer">{{
			      item.name
			    }}</span> -->
				<a :href="`${fileDownload}?id=${item.id}`">{{
				     item.name
				  }}</a> 
			  </el-row>
			  </div>
          <!-- <a v-if="isShow" v-for="(item, index) in fileList"
			    :key="index" :href="`${fileDownload}?id=${formData.scfjid}`">{{
               item.name
            }}</a> -->
            <el-upload
              v-else
              :disabled="isShow"
              :action="uploadUrl"
              :before-upload="beforeUpload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :on-error="handleError"
              :on-exceed="handleExceed"
              :file-list="fileList"
			  multiple
              :auto-upload="true"
            >
              <el-button
                size="small"
                type="primary"
                class="outButton"
                :disabled="isShow"
                >点击上传</el-button
              >
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="16" :offset="4">
          <el-form-item label="手册视频:" class="marginBot10">
            <dl v-if="isShow" @click="showVideo" class="defaultImg">
              <dt>
                <img src="@/assets/video.png" alt v-if="isImg" />
              </dt>
              <dd>{{ scspName }}</dd>
            </dl>
            <el-upload
              v-else
              :disabled="isShow"
              :action="uploadUrl"
              :limit="1"
              :before-upload="beforeVideoUpload"
              :on-preview="handlePreview"
              :on-remove="handleRemoveScsp"
              :on-success="handleVideoSuccess"
              :on-error="handleError"
              :on-exceed="handleExceed"
              :file-list="fileVideoList"
              :auto-upload="true"
            >
              <el-button
                size="small"
                type="primary"
                class="outButton"
                :disabled="isShow"
                >点击上传</el-button
              >
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="16" :offset="4">
          <el-form-item
            label="手册详情:"
            class="marginBot10"
            :class="{ editorStyle: isShow }"
          >
            <quill-editor
              :disabled="isShow"
              v-model="formData.scxq"
              ref="myQuillEditor"
              :options="quillOption"
            ></quill-editor>
            <el-input type="hidden" v-model="formData.scxq"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-dialog
      :visible.sync="dialogVisible"
      width="50%"
      :close-on-click-modal="false"
      class="videoDialog"
    >
      <video :src="`${fileDownload}?id=${formData.scspid}`" controls autoplay>
        您的浏览器不支持 video 标签。
      </video>
    </el-dialog>
    <div style="text-align: center">
      <el-button
        v-if="!isShow"
        @click="goSave(0)"
        type="primary"
        :loading="saveLoading"
      >
        <i class="iconfont">&#xe683;</i> 保存
      </el-button>
      <el-button
        v-if="!isShow"
        @click="goSave(1)"
        type="primary"
        class="iconfont icontijiao"
        :loading="tjLoading"
        >提交</el-button
      >
      <el-button @click="goBack" type="primary">
        <i class="iconfont">&#xe695;</i> 返回
      </el-button>
    </div>
  </div>
</template>
<script>
import quillConfig from "@/utils/quill-config.js";
import { addQuillTitle } from "@/utils/quill-title.js";
import { quillEditor } from "vue-quill-editor";
import { fileUpload, fileDownload } from "@/api/index";
import { validateFive } from "@/directives/validate";
import {
  helpAdd,
  helpDetail,
  getFileInfo,
  fileDelete,
  helpUpdate,
} from "@/api/publicfunction/helpDocument";
import {
  viewAllFileData
} from "@/api/publicfunction/announcement";
export default {
  data() {
    return {
      uploadUrl: `${fileUpload}`, //上传地址
      fileDownload: `${fileDownload}`,
      fileList: [],
      fileVideoList: [],
      quillOption: quillConfig,
      saveLoading: false,
      tjLoading: false,
      isShow: false,
      dialogVisible: false,
      isImg: false,
      detailLoading: false,
      formData: {
        wdbt: "",
        tjdz: "",
        gnmk: "",
        yhcj: "",
        scfjid: "", //手册附件id
        scspid: "", //手册视频id
        scxq: "",
        status: "",
        checkList: [],
      },
      scspName: "",
      scfjName: "",
      rules: {
        wdbt: [
          { required: true, message: "请输入文档标题", trigger: "blur" },
          { validator: validateFive, trigger: "blur" },
        ],
        tjdz: [
          { required: true, message: "请输入推荐读者", trigger: "blur" },
          { validator: validateFive, trigger: "blur" },
        ],
        gnmk: [
          { required: true, message: "请输入系统模块", trigger: "blur" },
          { validator: validateFive, trigger: "blur" },
        ],
        checkList: [
          {
            required: true,
            message: "请选择用户场景",
            trigger: ["blur", "change"],
          },
        ],
      },
      tjdzOptions: [
        { value: "粮食局", label: "粮食局" },
        { value: "批发市场", label: "批发市场" },
        { value: "储备粮公司", label: "储备粮公司" },
        { value: "区粮办", label: "区粮办" },
        { value: "承储库", label: "承储库" },
        { value: "购销公司(利达集团)", label: "购销公司(利达集团)" },
      ],
    };
  },
  created() {
    if (this.$route.query.state == "show") {
      this.isShow = true;
    }
    if (
      this.$route.query.state == "upDate" ||
      this.$route.query.state == "show"
    ) {
      this.getInitInfo();
    }
  },
  mounted() {
    addQuillTitle();
  },
  components: {
    quillEditor,
  },
  methods: {
    getInitInfo() {
      this.detailLoading = true;
      helpDetail(this.$route.query.wdId).then((res) => {
        this.formData = res;
		// this.formData.scfjid=this.formData.scfjid+','
        this.$set(this.formData, "checkList", res.yhcj.split(","));
        if (res.tjdz) {
          this.$set(this.formData, "tjdzarr", res.tjdz.split(","));
        }
        console.log(this.formData.tjdz, "tjdz");
        if (res.scfjid) {
          this.getFileFun(res.scfjid, "手册附件");
        }
        if (res.scspid) {
          this.getFileFun(res.scspid);
        }
        this.detailLoading = false;
      });
    },
    getFileFun(ids, mark) {
		let arr = ids.split(",")
		arr.forEach((item) =>{
			getFileInfo(item).then((res) => {
				console.log(res,'ppp-----------')
			  if (res.infoCode == 200) {
			    if (mark == "手册附件") {
			      this.fileList.push({
			          name: res.data[0].name,
					  id:item,
			          response: {
			            data: {
			              id: ids,
			            },
			          },
			        }) 
			      // this.scfjName = res.data[0].name;
			    } else {
			      this.fileVideoList = [
			        {
			          name: res.data[0].name,
			          response: {
			            data: {
			              id: ids,
			            },
			          },
			        },
			      ];
			      this.scspName = res.data[0].name;
			      if (this.$route.query.state == "show") {
			        //查看页面
			        this.isImg = true; //默认的视频图片
			      }
			    }
			  } else {
			    this.$message({
			      message: res.msg,
			      type: "error",
			      duration: 2000,
			    });
			  }
			});
		})
     
    },
    showVideo() {
      this.dialogVisible = true;
    },
    commonSaveFun(type) {
      this.formData.status = type;
      this.formData.yhcj = this.formData.checkList.join(",");
      this.formData.tjdz = this.formData.tjdzarr.toString();
	  // if (this.fileList.length > 0) {
	  //   this.formData.scfjid = "";
	  //   let arr = [];
	  //   this.fileList.forEach((item) => {
	  //     arr.push(item.id);
	  //   });
	  //   this.formData.scfjid = arr.join(",");
	  // } else {
	  //   this.formData.scfjid = "";
	  // }
	  // substr(0, basic.length - 1)
	  
	  // this.formData.scfjid.substr(0, this.formData.scfjid.length - 1)
	  if(this.formData.scfjid.substr(-1) == ','){
		this.formData.scfjid=this.formData.scfjid.substr(0, this.formData.scfjid.length - 1)
		console.log(this.formData.scfjid.substr(0, this.formData.scfjid.length - 1),'o0-----------')  
	  }
      if (type == 0) {
        this.saveLoading = true;
      } else {
        this.tjLoading = true;
      }
      if (this.$route.query.state == "upDate") {
        helpUpdate(this.formData).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: type == 0 ? "保存成功" : "提交成功",
              type: "success",
              duration: 2000,
            });
            this.goBack();
          } else {
            this.$message({
              message: res.msg,
              type: "error",
              duration: 2000,
            });
            if (type == 0) {
              //草稿
              this.saveLoading = false;
            } else {
              this.tjLoading = false;
            }
          }
        });
      } else {
        helpAdd(this.formData).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: type == 0 ? "保存成功" : "提交成功",
              type: "success",
              duration: 2000,
            });
            this.goBack();
          } else {
            this.$message({
              message: res.msg,
              type: "error",
              duration: 2000,
            });
            if (type == 0) {
              //草稿
              this.saveLoading = false;
            } else {
              this.tjLoading = false;
            }
          }
        });
      }
    },
    goSave(type) {
      if (type == 0) {
        //保存
        this.commonSaveFun(type);
      } else {
        this.$refs.formData.validate((valid) => {
          if (valid) {
            this.commonSaveFun(type);
          } else {
            return false;
          }
        });
      }
    },
    goBack() {
      this.$router.go(-1);
    },
    //--------------------  手册附件开始-----------------------
    handleSuccess(res, file, fileList) {
      if (res.infoCode == 200) {
		  // this.fileList=res.data
		  // console.log(this.fileList)
		  // this.formData.scfjid=this.formData.scfjid+','
		  console.log(this.formData.scfjid,'888111------')
		  console.log(this.formData.scfjid.substr(-1),'888111------')
		  console.log(this.formData.scfjid.substr(-1) == ',')
		  if(this.formData.scfjid.substr(-1) == ',' || this.formData.scfjid == ''){
			this.formData.scfjid += res.data.id+','; 
		  }else{
			this.formData.scfjid +=','+res.data.id;
		  }
        
      } else {
        //ie下上传失败走这里了(文件过大的情况，其他情况未知)
        console.log("成功成功方法里", res + 2222, file, fileList);
        this.fileList = [];
        if (res.msg) {
          this.$message({
            message: `${res.msg}`,
            type: "error",
            duration: 2000,
          });
        } else {
          this.$message({
            message: "上传失败",
            type: "error",
            duration: 1000,
          });
        }
      }
    },
    handleError(err, file, fileList) {
      console.log("失败失败方法里", err, file, fileList);
      this.$message({
        message: "上传失败",
        type: "error",
        duration: 1000,
      });
    },
    handleRemove(file, fileList) {
		let arr =[]
		console.log(file,'ppp---000-----')
		// arr =file.response.data.id.split(",")
		let needId=''
		if(file.id){
			 needId = file.id;
		}else{
			needId = file.response.data.id
		}
		
		// arr.forEach((item) =>{
		fileDelete(needId).then((res) => {
		  if (res.infoCode != 200) {
			this.$message({
			  message: res.msg,
			  type: "error",
			  duration: 2000,
			});
		  }else{
			  let scfjArr=this.formData.scfjid.split(',')
			  console.log(scfjArr,'oo9999-====--------------')
			  scfjArr.forEach((info,index) =>{
				console.log(index,'5555555552------------')
				if(needId == info){
					console.log(index,'998877-----------')
					scfjArr.splice(index,1)
					console.log(scfjArr,'9998=====')
					this.formData.scfjid=scfjArr.join(',')
					console.log(this.formData.scfjid,'00011=============')
				}
			  })
		  }
		});
    },
	handleRemoveScsp(file, fileList){
		const needId = file.response.data.id;
		fileDelete(needId).then((res) => {
		  if (res.infoCode != 200) {
			this.$message({
			  message: res.msg,
			  type: "error",
			  duration: 2000,
			});
		  }
		});
		if (this.formData.scfjid == needId) {
		  this.formData.scfjid = "";
		}
		if (this.formData.scspid == needId) {
		  this.formData.scspid = "";
		}
	},
    handlePreview(file) {
      window.location.href = `${fileDownload}?id=${file.response.data.id}`;
    },
    // 上传前调用方法
    beforeUpload(file) {
      if (file.size > 500 * 1024 * 1024) {
        this.$message({
          message: "上传文件大小不能超过500M",
          duration: 2000,
          type: "warning",
        });
        return false;
      }
    },
    handleExceed(files, fileList) {
      // this.$message.warning(
      //   `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
      //     files.length + fileList.length
      //   } 个文件`
      // );
    },
    //--------------------  手册附件结束-----------------------
    //--------------------  手册视频开始-----------------------
    handleVideoSuccess(res, file) {
      if (res.infoCode == 200) {
        this.formData.scspid = res.data.id;
      } else {
        this.fileVideoList = [];
        if (res.msg) {
          this.$message({
            message: `${res.msg}`,
            type: "error",
            duration: 1000,
          });
        } else {
          this.$message({
            message: "上传失败",
            type: "error",
            duration: 1000,
          });
        }
      }
    },
    beforeVideoUpload(file) {
      if (file.size > 500 * 1024 * 1024) {
        this.$message({
          message: "视频大小不能超过500M",
          duration: 2000,
          type: "warning",
        });
        return false;
      }
      // if (['video/mp4', 'video/ogg', 'video/flv','video/avi','video/mov','video/wmv','video/rmvb','video/rm','video/3gp'].indexOf(file.type) == -1) {
      //     this.$message.warning('请上传正确的视频格式');
      //     return false;
      // }
      if (file.type !== "video/mp4") {
        this.$message({
          message: "请上传正确的视频格式",
          duration: 2000,
          type: "warning",
        });
        return false;
      }
    },
    //--------------------  手册视频结束-----------------------
  },
};
</script>
<style lang="scss" scoped>
.helpManagerAddPage {
  .ql-editor {
    min-height: 150px;
  }
  .editorStyle .ql-toolbar.ql-snow {
    //查看页面让富文本头部隐藏
    // display: none;
  }
  .editorStyle .ql-toolbar.ql-snow + .ql-container.ql-snow {
    //查看页面用
    border-top: 1px solid #ccc;
  }
  .marginBot10 {
    margin-bottom: 10px;
  }
  .yhcjStyle {
    margin-bottom: 5px;
    .el-form-item__label,
    .el-form-item__content {
      line-height: 25px;
    }
    .el-form-item__error {
      padding-top: 0px;
      top: 24px;
    }
  }
  .defaultImg {
    display: inline-block;
    cursor: pointer;
    text-align: center;
    &:hover {
      dd {
        color: #06c;
      }
    }
  }
  .videoDialog {
    video {
      object-fit: fill;
      width: 100%;
      height: 500px;
    }
    .el-dialog__header {
      padding: 0 !important;
    }
    .el-dialog__headerbtn .el-dialog__close {
      position: relative;
      left: 6px;
      top: -7px;
      color: #333 !important;
    }
  }
}
</style>