<template>
  <div class="app-container setting-main">
    <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">当前批次基本信息</div>
      <el-row class="setting-content">
        <el-col :span="6"><div class="">批次号：{{info.harvestBatchId}}</div></el-col>
        <el-col :span="6"><div class="">所属商户：{{info.belongBusinessName}}</div></el-col>
        <el-col :span="6"><div class="">商品名称：{{info.goodsName}}</div></el-col>
      </el-row>
    </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>
           <el-select
             v-model="templateId"
             class="mr-10"
             placeholder="选择模板">
             <el-option :value="item.templateId" :label="item.templateName" v-for="(item,index) in tempList" :key="index"></el-option>
           </el-select>
           <el-button type="info" plain :disabled="existHasOnChainItem || !templateId" @click="importModel">导入模板</el-button>
           <el-button class="mr-10" type="primary" @click="saveModel">保存为模板</el-button>
        </div>
      </div>
      <div>
        <div
        class="setting-operateList"
        v-for="(item,index) in info.links"
        :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 class="setting-tag mr-6">{{item.isChainState?'已上传':'未上传'}}</div>
              <span class="fs-12 mr-6" v-if="!item.isChainState">自动上传</span>
              <el-switch v-model="item.chainState" :active-value="1" :inactive-value="0" v-if="!item.isChainState"></el-switch>
            </div>
            <div style="display: flex;align-items: center;">
              <div v-if="item.chainState && item.isChainState">
                <span class="fs-12 mr-6" >扫码展示</span>
                <el-switch v-model="item.scanShow" :active-value="true" :inactive-value="false"></el-switch>
              </div>
              <el-popconfirm
                v-if="!item.isChainState"
                title="确定删除吗？"
                @confirm="info.links.splice(index,1)">
                <el-button slot="reference" type="text" class="mlr-10">删除</el-button>
              </el-popconfirm>
              <div class="flex-col flex-allcenter">
                <i class="el-icon-caret-top operate-icon" @click="tempSerial(info.links,index)" :class="[index!=0?'operate-active':'']"></i>
                <i class="el-icon-caret-bottom operate-icon" @click="downtempSerial(info.links,index)" :class="[info.links.length != 1 && info.links.length-1 != index ?'operate-active':'']"></i>
              </div>
            </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.operateDetails"
            :chainState="0"
            :typeList="typeList"
            :type="'links'">
            </operateInfo>
          </div>
        </div>
        <div slot="empty" v-if="info.links && info.links.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>

    <!-- 保存模板 -->
    <el-dialog
    title="保存为模板"
    :visible.sync="dialogSave"
    width="600px">
      <el-form
        ref="formSave"
       :model="formSave"
       :rules="rulesSave"
       label-position="top"
       label-width="100px">
        <el-form-item label="模板名称" prop="linkName">
          <el-input v-model="formSave.linkName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogSave = false">取 消</el-button>
        <el-button type="primary" @click="submitSaveTemp">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import { getLinkConfig , updateLinkConfig , createLinkConfig  } from '@/api/production/harvestBatch';
  import { exportLinkConfig } from '@/api/product/harvestBatch';
  import { getDictDataListByType } from '@/api/system/dict/data';
  import { getTempListGoodsId , copyToTemplate , getTemplateDetail } from '@/api/configure/traceTemplate';
  import EmptyTable from '@/components/EmptyTable'
  import operateInfo from '@/components/Customer/operateInfo';
  import fileUpload from '@/components/FileUpload';
import { trace } from 'mathjs';
  export default{
    components: {
      EmptyTable,
      operateInfo,
      fileUpload
    },
    data(){
      return{
        // 页面获取获取到的数据
        info:{},
        // 临时
        value: '',
        // 可选种类列表
        typeList: [],
        // 模板列表
        tempList: [],
        // 表单
        form:{},
        // 规则 rules
        rules:{
          linkName: [
            { required: true, message: '请输入环节名称', trigger: 'blur' }
          ],
        },
        // 模板保存规则 rules
        rulesSave:{
          linkName: [
            { required: true, message: '请输入环节名称', trigger: 'change' }
          ],
        },
        // 环节导入弹窗
        dialogImport: false,
        // 模板保存弹窗
        dialogSave: false,
        // 环节导入表单
        formImport: {},
        // 模板保存表单
        formSave:{},
        // 环节导入文件类型
        fileType: ['pdf'],
        // 当前选择的模板id
        templateId:'',
        existHasOnChainItem: false,
        // 上传文件参数
        fileList: [],
        fileSize: 0.5,
        fileLimit: 1,
        fileType: ['json'],
        uploadFileUrl: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/upload", // 请求地址
      }
    },
    created() {
      let id = this.$route.query.id;
      this.getLinkConfig(id);
    },
    methods:{
      // 初始化数据
      async initDate(info){
        let typeParams = {
          page: 1,
          pageSize: 100,
          type: 'operate_detail_type',
        };
        let res = await getDictDataListByType(typeParams);
        this.typeList = res.data;
        console.log('类型列表',this.typeList)
        let getTempForm = {
          goodsId: info.goodsId,
        };
        let resTemp = await getTempListGoodsId(getTempForm);
        this.tempList = resTemp.data;
        console.log('模板列表',resTemp)
        // 判断是否含有已上链的环节
        info.links.map(item => {
          if(item.chainState === 1) {
            this.existHasOnChainItem = true;
          }
        })

      },
      addLink(){
        this.info.links.push({
          isExpand: false,
          linkName: '新建环节',
          operateDetails: [],
        });
      },
      // 获取环节信息
      getLinkConfig(id){
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        getLinkConfig({id}).then((res)=>{
          console.log('环节信息',res)
          let info = res.data;
          res.data.links.length && res.data.links.map(item =>{
            item.isExpand = false;
            item.isChainState = item.chainState?1:0;
            let operateDetails = item.operateDetails;
            operateDetails.length && operateDetails.map(items=>{
              if(items.type == 7){
                items.content = JSON.parse(items.content);
                items.mapContent = items.content;
              }
            });
          });
          this.info = info;
          console.log('info',this.info);
          loading.close();
          this.initDate(info);
        });
      },
      //向上移动  list是一个数组，index是当前的索引值
      tempSerial(list, index) {
        if(list.length == 1 ) return;
        if (index != 0) {
          list[index] = list.splice(index - 1, 1, list[index])[0]
        } else {
          list.push(list.shift())
        }
      },
      //向下移动  list是一个数组，index是当前的索引值
      downtempSerial(list, index) {
        if(list.length == 1 && list.length-1 == index) return;
        if (index != list.length - 1) {
          list[index] = list.splice(index + 1, 1, list[index])[0]
        } else {
          list.unshift(list.splice(index, 1)[0])
        }
      },
      // 保存配置
      async submitSave(){
        let state = await this.checkSubmit();
        console.log('保存-状态是否符合',state);
        if(state){
          let form = {
            id: this.$route.query.id,
            linkInfos: this.info.links,
          };

          let res = await updateLinkConfig(form);
          if(res.data){
            this.$message.success("保存成功"); 
            let id = this.$route.query.id;
            this.getLinkConfig(id);
          }
        }
      },

      // 环节导出
      async linksExport(){
        let rest = await exportLinkConfig({id:this.$route.query.id});
        this.$download.json(JSON.stringify(rest),'环节信息.json');
      },

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

      // 导入模板
      async importModel(){
        let { data } = await getTemplateDetail({templateId: this.templateId});
        data.map((item,index)=>{
          item.isExpand = false;
          if(index == 0) item.isExpand = true;
          item.id = null;
          item.isChainState = 0;
          item.chainState = 0;
          item.operateDetails = JSON.parse(JSON.stringify( item.traceLinkItems ));
          item.operateDetails && item.operateDetails.map(items=>{
            if(items.type == 7){
              items.content = JSON.parse(items.content);
              items.mapContent = items.content;
            }
          });
        });
        this.info.links = data;
      },

      // 保存为模板
      saveModel(){
        this.dialogSave = 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.links;
        if(list.length > 0){
          list.map((item,index)=>{
            item.sort = index+1;
            if(item.linkName == '') isName = true;
            // if(item.id) isId = true;
            if(item.operateDetails.length==0) isDate = true;
            item.operateDetails.length && item.operateDetails.map(items=>{
              if( !items.type ) isContent = true;
              console.log(items.type);
              if( items.type != 5 && items.type != 6 && !items.title ) isTitle = true;
              //地图
              if(items.type == '7') items.content = JSON.stringify(items.mapContent);
            });
          });
        }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;
      },

      // 提交模板保存
      submitSaveTemp(){
        this.$refs['formSave'].validate(async (valid) => {
          if (valid) {
            let state = await this.checkSubmit();
            console.log('保存模板-状态是否符合',state);
            if(state){
              let links = JSON.parse(JSON.stringify(this.info.links));
              links.map(item=>{
                item.linkItems = item.operateDetails;
              });
              let form = {
                belongBusinessId: this.info.belongBusinessId,
                goodsId: this.info.goodsId,
                links,
                templateName: this.formSave.linkName,
              };
              let res = await copyToTemplate(form);
              if(res.data){
                this.$message.success("保存模板成功");
                this.dialogSave = false;
                this.formSave = {};
              }
              console.log('保存模板结果',res);
            }
          }
        });
      },
      // ------------------------ 导入模板相关事件 ------------------------
      // 导入模板本质不经过接口，前端直接读取文件内容，覆盖本地模板
      // 上传前校检格式和大小
      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.operateDetails.length>0 && item.operateDetails.map(items=>{
                if(items.type == 7){
                  items.content = JSON.parse(items.content);
                  items.mapContent = items.content;
                }
              });
            });
            that.dialogImport = false;
            that.info.links = val;
          }
        }
      },

    }
  }
</script>

<style>
</style>
