<template>
  <div class="app-container">
    <div class="app-container-search main-radius">
      <h1 style="margin: 0;">配置溯源模板</h1>
    </div>
    <div class="app-container-search main-bgcolor main-radius setting-container">
      <div class="setting-title flex-jcenter">
        <div class="">溯源环节信息</div>
        <div class="">
          <el-button class="" @click="linksExport">溯源环节导出</el-button>
          <el-button class="mr-10" @click="linksImport">溯源环节导入</el-button>
        </div>
      </div>
      <div>
        <div
        class="setting-operateList"
        v-for="(item,index) in info"
        :key="index">
          <div class="flex-jcenter">
            <div class="setting-title">
              <i class="el-icon-arrow-down mr-10" @click="item.isExpand = !item.isExpand" :class="[item.isExpand?'expand-active':'expand']"></i>
              <span class="mr-6">{{item.linkName}}</span>
            </div>
            <div style="display: flex;align-items: center;">
              <el-popconfirm
                v-if="!item.isChainState"
                title="确定删除吗？"
                @confirm="info.splice(index,1)">
                <el-button slot="reference" type="text" class="mlr-10">删除</el-button>
              </el-popconfirm>
            </div>
          </div>
          <div class="infos" :class="[item.isExpand?'infos-active':'']">
            <el-form ref="form" :model="form" label-width="80px">
              <el-row>
                <el-col :span="6">
                  <el-form-item label="环节名称" prop="linkName">
                    <el-input v-model="item.linkName"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <operateInfo
            :operateDetails="item.traceLinkItems"
            :chainState="item.chainState"
            :typeList="typeList"
            :type="'links'">
            </operateInfo>
          </div>
        </div>
        <div slot="empty" v-if="info.length == 0">
            <EmptyTable />
        </div>
        <div class="setting-btn-area" @click="addLink">
          <i style="font-size: 14px;" class="el-icon-plus"></i>
          <div class="buttonText">添加环节</div>
        </div>
      </div>
    </div>
    <div class="setting-footer-btn">
      <el-button @click="$router.go(-1);">取消</el-button>
      <el-button type="primary" @click="submitSave">保存</el-button>
    </div>

    <!-- 溯源环节上传 -->
    <el-dialog
    title="溯源环节上传"
    :visible.sync="dialogImport"
    width="600px">
      <el-upload
        class="upload-demo"
        drag
        :limit="fileLimit"
        :auto-upload="false"
        :before-upload="handleBeforeUpload"
        :on-exceed="handleExceed"
        :on-change="handleChange"
        :file-list="fileList"
        :action="uploadFileUrl">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传json文件，且不超过500kb</div>
      </el-upload>
    </el-dialog>

  </div>
</template>

<script>
import { getTemplateDetail , updateLinkConfig , importLinkConfig , exportLinkConfig } from '@/api/configure/traceTemplate';
import { getDictDataListByType } from '@/api/system/dict/data';
import operateInfo from '@/components/Customer/operateInfo';
import EmptyTable from '@/components/EmptyTable'
export default {
  name: "TraceLink",
  components: {
    operateInfo,
    EmptyTable
  },
  data() {
    return {
      // 页面获取获取到的数据
      info:[],
      // 环节导入弹窗
      dialogImport: false,
      // 环节导入表单
      formImport: {},
      // 表单参数
      form: {},
      // 可选种类列表
      typeList: [],
      // 上传文件参数
      fileList: [],
      fileSize: 0.5,
      fileLimit: 1,
      fileType: ['json'],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/upload", // 请求地址
    };
  },
  created() {
    this.initDate();
  },
  mounted() {

  },
  activated() {
    this.initDate();
  },
  methods: {
    async initDate(){
      let templateId = this.$route.query.templateId;
      console.log('query参数',templateId);
      this.getInfo(templateId);
      let typeParams = {
        page: 1,
        pageSize: 100,
        type: 'operate_detail_type',
      };
      let res = await getDictDataListByType(typeParams);
      this.typeList = res.data;
      console.log('类型列表',this.typeList)
    },

    async getInfo(templateId){
      let { data } = await getTemplateDetail({templateId});
      data.map(item=>{
        item.isExpand = false;
        item.traceLinkItems.map(items=>{
          if(items.type == 7){
            items.content = JSON.parse(items.content);
            items.mapContent = items.content;
          }
        });
      })
      this.info = data;
      console.log('环节信息',data);
    },

    addLink(){
      this.info.push({
        isExpand: false,
        linkName: '新建环节',
        traceLinkItems: [],
      });
    },

    // 导出溯源环节配置
    async linksExport(){
      let templateId = this.$route.query.templateId;
      if(!templateId){
        this.$message.error('溯源模板id不能为空')
        return false;
      }
      let res = await exportLinkConfig({templateId});
      this.$download.json(JSON.stringify(res),'溯源环节配置.json');
      console.log('导出溯源环节配置',res);
    },

    // 环节导入
    linksImport(){
      this.dialogImport = true;
    },

    // 验证links是否可提交
    checkSubmit(){
      let isName = false;//环节名称是否存在空值
      // let isId = false;//环节是否存在id，有则更新，无则创建
      let isContent = false;//类似是否存在空值
      let isTitle = false;//类型为5或6时，为无标类型，标题可为空，其他类型，标题不能为空。
      let isDate = false;//环节内数据不能为空
      let list = this.info;
      if(list.length > 0){
        list.map((item,index)=>{
          item.sort = index+1;
          if(item.linkName == '') isName = true;
          // if(item.id) isId = true;
          if(item.traceLinkItems.length==0) isDate = true;
          item.traceLinkItems.length && item.traceLinkItems.map(items=>{
            if( !items.type ) isContent = true;
            if( items.type != 5 && items.type != 6 && !items.title ) isTitle = true;
            //地图
            if(items.type == '7') items.content = JSON.stringify(items.mapContent);
          });
          item.linkItems = JSON.parse(JSON.stringify(item.traceLinkItems));
        });
      }else{
        this.$message.error("环节不能为空");
        return false;
      }
      if(isName){
        this.$message.error("环节名称不能为空");
        return false;
      }
      if(isContent){
        this.$message.error("环节数据类型不能为空");
        return false;
      }
      if(isTitle){
        this.$message.error("环节数据标题不能为空");
        return false;
      }
      if(isDate){
        this.$message.error("环节内数据不能为空");
        return false;
      }
      // if(isId){
      //   this.$message.error("");
      //   return false;
      // }
      return true;
    },


    // 保存配置
    async submitSave(){
      let state = await this.checkSubmit();
      console.log('保存-状态是否符合',state);
      if(state){
        let form = {
          id: this.$route.query.id,
          links: this.info,
        };

        let res = await updateLinkConfig(form);
        if(res.data){
          this.$message.success("保存成功");
          this.$router.go(-1);
        }
      }
    },

    // ------------------------ 导入模板相关事件 ------------------------
    // 导入模板本质不经过接口，前端直接读取文件内容，覆盖本地模板
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },

    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.fileLimit} 个!`);
    },

    // 文件改变
    handleChange(file, fileList){
      if( fileList.length > 0 ){
        let files = fileList[0].raw;
        let reader = new FileReader();
        reader.readAsText(files,'UTF-8');
        let that = this;
        reader.onload = function(e){
          let val = JSON.parse(e.target.result);
          val.map((item,index)=>{
            item.isExpand = false;
            if(index == 0) item.isExpand = true;
            item.chainState = 0;
            item.isChainState = 0;
            item.traceLinkItems.length && item.traceLinkItems.map(items=>{
              if(items.type == 7){
                items.content = JSON.parse(items.content);
                items.mapContent = items.content;
              }
            });
          });
          that.dialogImport = false;
          that.info = val;
          that.fileList = [];
        }
      }
    },

  }
};
</script>
