<template>
  <div style="display:inline-block;margin-left:2px; margin-right:2px;">
    <el-button v-if="!isReleaseView" icon="el-icon-document-copy" type="primary" size="mini" @click="openDialog()" :loading="loadingStatus"><span>使用模板</span></el-button>
    <el-button icon="el-icon-document-add" type="primary" size="mini" @click="openSavDialog()"><span>保存模板</span></el-button>
    
    <el-dialog custom-class="save-dialog" :visible.sync="dialogSavFormVisible"  title="保存模板" :modal-append-to-body="false"
      :lock-scroll="false" :show-close="true" :close-on-click-modal="false" :close-on-press-escape="false" v-dialogDrag @close="cancelDialog()">
      <el-form ref="dialogForm" :model="tdtmplDialog" label-width="120px" label-position="right" label-suffix=":" :rules="rules">
        <el-row style="margin-top:30px;">
          <el-col :span="22">
            <el-form-item label="模板名称" prop="tmplnam">
              <span>{{tdtmplDialog.tmpltyp}}-{{routePathCode.toUpperCase()}}-{{tdtmplDialog.ownref}}-</span>
              <el-input style="width:60%;" v-model="tdtmplDialog.tmplnam" maxlength="60"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="模板类型" prop="tmpltyp">
              <el-radio-group v-model="tdtmplDialog.tmpltyp">
                <el-radio label="C" :disabled="isDisabled">公共</el-radio>
                <el-radio label="O">机构</el-radio>
                <el-radio label="P">个人</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        
      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button @click="cancelDialog">取 消</el-button>
          <el-button type="primary" @click="submitDialog" :loading="loadingSavStatus">确 定</el-button>
      </div>
    </el-dialog>
    
    <el-dialog :visible.sync="dialogFormVisible" title="交易信息模板" :modal-append-to-body="true" :append-to-body="true" ref="searchTmplDialog"
      :lock-scroll="false" :show-close="true" :close-on-click-modal="false" :close-on-press-escape="false" width="60%" v-dialogDrag @close="closeCallBack()">
      <el-form :model="tdtmpl" ref="searchForm" label-width="120px" label-position="right" size="small">
        <c-col :span="24">
          <c-col :span="12">
            <c-form-item label="模板名称" prop="tmplnam">
              <el-input v-model="tdtmpl.tmplnam"></el-input>
            </c-form-item>
          </c-col>
          <c-col :span="12">
            <c-form-item label="模板类型" prop="tmpltyps">
              <c-checkbox-group v-model="tdtmpl.tmpltyps">
                <el-checkbox style="float: left;" label="C">公共</el-checkbox>
                <el-checkbox style="float: left;" label="O">机构</el-checkbox>
                <el-checkbox style="float: left;" label="P">个人</el-checkbox>
              </c-checkbox-group>
            </c-form-item>
          </c-col>
        </c-col>
        <c-col :span="24">
          <c-col :span="12">
            <c-form-item label="业务编号" prop="ownref">
              <el-input v-model="tdtmpl.ownref"></el-input>
            </c-form-item>
          </c-col>
          <c-col :span="12">
            <el-form-item label="创建日期" style="width: 100%">
              <el-date-picker v-model="dateArrary" @change="setDate()" value-format="yyyy-MM-dd" type="daterange" start-placeholder="开始日期" range-separator="至" end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </c-col>
        </c-col>
        <c-col :span="24">
          <c-col :span="12">
            <c-form-item label="创建人名称" prop="tmplusr">
              <el-input v-model="tdtmpl.tmplusr"></el-input>
            </c-form-item>
          </c-col>
        </c-col>
        <c-col :span="24">
          <span style="float: right">
            <el-button size="small" @click="resetFormFields('searchForm')">重置</el-button>
            <el-button type="primary" icon="el-icon-search" size="small" @click="searchTable()" :loading="searchLoading">查询</el-button>
          </span>
        </c-col>
        <c-col :span="24">
          <c-paging-table :data="tableData" ref="tdtmplTableRef" :pageSize="tdtmpl.pageSize" :pageNumber="tdtmpl.pageNum" :total="tdtmpl.total"
            @queryFunc="queryFunc" :border="true">
            <el-table-column label="模板类型" prop="tmpltypnam" min-width="10%">
              <template slot-scope="scope">{{scope.row.tmpltypnam}}</template>
            </el-table-column>
            <el-table-column label="业务编号" prop="ownref" min-width="15%">
              <template slot-scope="scope">{{scope.row.ownref}}</template>
            </el-table-column>
            <el-table-column label="模板名称" prop="tmplnam" min-width="40%">
              <template slot-scope="scope">{{scope.row.tmplnam}}</template>
            </el-table-column>
            <el-table-column label="创建人名称" prop="tmplusr" min-width="10%">
              <template slot-scope="scope">{{scope.row.tmplusr}}</template>
            </el-table-column>
            <el-table-column label="创建日期" prop="tmpldat" min-width="15%">
              <template slot-scope="scope">{{scope.row.tmpldat}}</template>
            </el-table-column>
            <el-table-column label="操作" min-width="15%">
              <template slot-scope="scope">
                <el-button @click="useInfoDialog(scope.row.inr)" type="primary" size="mini">使用</el-button>
                <el-button @click="deleteInfoDialog(scope.row.inr)" 
                v-if="!(scope.row.tmpltyp == 'C' && isShow)"  type="danger" size="mini">删除</el-button>
              </template>
            </el-table-column>
          </c-paging-table>
        </c-col>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import TdTmplModel, { Pattern } from "./TdTmplModel.js";
import { queryByPage, getInfo, deleteInfo, saveInfo } from "~/service/manage/tdtmpl.js";
import Utils from "~/utils";
import commonFunctions from "~/mixin/commonFunctions.js";
import templateData from './template.js'
import _ from 'lodash'
import commonDepend from "~/mixin/commonDepend.js";
export default {
  inject: ["root"],
  mixins: [commonFunctions, commonDepend],
  props: ['modelStr','codes'],
  data(){
    return{
      tdtmpl: new TdTmplModel().data.TdTmpl,
      tdtmplDialog: new TdTmplModel().data.TdTmpl,
      rules: Pattern,
      tableData: [],
      deleteInr: '',
      dateArrary: [],
      dialogSavFormVisible:false,
      dialogFormVisible:false,
      loadingSavStatus: false,
      loadingStatus:false,
      isDisabled: true,
      isShow:true,
      searchLoading:false,
    }
  },
  computed:{
    isReleaseView () {
      return this.$route.path.startsWith("/review");
    },
    routePathCode() {
      let routePath = this.$route.path
			let code = routePath.substring(routePath.lastIndexOf('/') + 1, routePath.length)
			if (code.indexOf('review-') > -1) {
				code = code.substr(code.indexOf('-') + 1, code.length)
			}
      console.log('routerCode', code)
      return code
    }
  },
  mounted(){
    this.searchTable();
    this.changeIsDisabled();
    console.log(this.$route)
	},
  methods:{
    getModelStr(){
      return JSON.stringify(this.modelStr);
    },
    // 使用事件
    useInfoDialog(inr){
      this.tdtmpl.inr = inr;
      getInfo(this.tdtmpl).then((res)=>{
        if(res.respCode == 'AAAAAA'){
          let tmpltxt = res.data.tmpltxt;
          let resModel = JSON.parse(tmpltxt)
          let trnNameList = Object.keys(templateData)
          trnNameList.forEach((nam) => {
            if (nam.indexOf(this.routePathCode) > -1) {
              let curTemp = templateData[nam]
              let codeList = Object.keys(curTemp)
              codeList.forEach((cod) => {
                let curVal = _.get(resModel, cod)
                _.set(this.root.model, cod, curVal)
                let curModelVal = _.get(this.root.model, cod)
                if (curModelVal != curVal) {
                  if (typeof curModelVal != 'object') {
                    if (cod.indexOf('.') > -1) {
                      let ind = cod.lastIndexOf('.')
                      let preStr = cod.substring(0, ind)
                      let preObj =  _.get(this.root.model, preStr)
                      let nextStr = cod.substring(ind + 1, cod.length)
                      this.customAddModify(preObj, nextStr);
                    } else {
                      this.customAddModify(this.root.model, cod);
                    }
                  }
                }
              })
            }
          })
        }
      }).catch((err)=>{
        this.$notify.error("查询失败!");
      });
      
      this.dialogFormVisible = false;
    },
    // 打开模态框
    openDialog(){
      this.loadingStatus = true;
      this.tdtmpl.tmpltyps = ['O'];
      this.searchTable();
      this.dialogFormVisible = true;
    },

    // 日期赋值
    setDate(){
      this.tdtmpl.bgndat = this.dateArrary[0];
      this.tdtmpl.enddat = this.dateArrary[1];
    },

    // 重置表单数据
    resetFormFields(formName){
      this.dateArrary = [];
      this.tdtmpl.inr = '';
      this.tdtmpl.tmpltyp = '';
      this.tdtmpl.ownref = '';
      this.tdtmpl.tmpltypnam = '';
      this.tdtmpl.tmpltxt = '';
      this.tdtmpl.tmpltrn = '';
      this.tdtmpl.tmpldat = '';
      this.tdtmpl.bgndat = '';
      this.tdtmpl.enddat = '';
      this.tdtmpl.tmpltyps = [];
      this.tdtmpl.tmplbchs = [];
      this.tdtmpl.tmplnam = '';
      this.tdtmpl.tmplusr = '';
    },

    // 获取分页组件数据,为请求数据赋值
    queryFunc(pageNumber, pageSize) {
      this.tdtmpl.pageNum = pageNumber;
      this.tdtmpl.pageSize = pageSize;
      this.searchTable();
    },

    // 列表查询
    searchTable(){
      this.tdtmpl.tmpltrn = this.routePathCode;
      this.searchLoading = true;
      queryByPage(this.tdtmpl).then((res)=>{
        this.searchLoading = false;
        this.tableData = res.data.list;
        this.tdtmpl.total = res.data.total;
        this.tdtmpl.pageNum = res.data.pageNumber;
        this.tdtmpl.pageSize = res.data.pageSize;
        this.loadingStatus = false;
        if(this.$store.state.UserContext.currentOrg.level === 0){
          this.isShow = false;
        } else {
          this.isShow = true;
        }
      }).catch((err)=>{
        this.searchLoading = false;
        this.$notify.error("查询失败!");
        this.loadingStatus = false;
      });
    },

    // 【删除】按钮
    deleteInfoDialog(inr){
      this.deleteInr = inr;
      this.$confirm("是否确认删除?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
        })
        .then(()=>{
          this.deleteDialogInfo();
        })
        .catch(() => {
            this.$message({
                type: "info",
                message: "已取消删除",
            });
        });
    },

    // 【删除-确定】删除
    deleteDialogInfo(){
      this.tdtmpl.inr = this.deleteInr;
      deleteInfo(this.tdtmpl)
        .then((res)=>{
            this.$notify.success("删除成功!");
            this.deleteInr = null;
            // 刷新列表
            this.searchTable();
        })
        .catch((err)=>{
            this.$notify.error("删除失败!");
        });
    },

    // 关闭回调函数
    closeCallBack(){
      this.tableData = [];
      this.tdtmpl.tmplnam = '';
      this.tdtmpl.ownref = '';
      this.tdtmpl.tmplusr = '';
      this.tdtmpl.total = 0;
      this.tdtmpl.pageNum = 1;
      this.tdtmpl.pageSize = 5;
    },
    // 判断当前所属机构是否总行
    changeIsDisabled(){
      if (this.$store.state.UserContext.currentOrg && this.$store.state.UserContext.currentOrg.level === 0) {
        this.isDisabled = false;
			} else {
        this.isDisabled = true;
      }
    },
    // 解析modelStr,获取ownref和aplNam
    getOwnrefAndAplNam(){
      var tmplModel = JSON.parse(this.getModelStr());
      let buildCommonData = this.root.buildCommonData(tmplModel, this.root.trnName)
      if (buildCommonData.rec.ownref == '') {
        this.$message({type: "warning",message: "请首先输入交易Reference编号"});
        return;
      }
      this.dialogSavFormVisible = true;
    },

    // 打开模态框
    openSavDialog(){
      this.changeIsDisabled();
      this.tdtmplDialog.tmpltyp = 'O';
      this.getOwnrefAndAplNam();
    },

    // 【取消】按钮
    cancelDialog(){
      this.dialogSavFormVisible = false;
      this.tdtmplDialog.inr = '';
      this.tdtmplDialog.ownref = '';
      this.tdtmplDialog.tmplnam = '';
      this.tdtmplDialog.tmpltyp = '';
      this.tdtmplDialog.tmpltxt = '';
      this.tdtmplDialog.tmplbchs = [];
      this.tdtmplDialog.tmpltrn = '';
      this.tdtmplDialog.tmplusr = '';
      this.tdtmplDialog.tmpldat = '';
      this.$refs['dialogForm'].resetFields();
    },

    // 【确定】按钮
    submitDialog(){
      this.$refs.dialogForm.validate((validated) => {
        if(validated){
          this.loadingSavStatus = true;
          this.tdtmplDialog.tmpltxt = this.getModelStr();
          this.tdtmplDialog.tmpltrn = this.routePathCode;
          saveInfo(this.tdtmplDialog)
            .then((res)=>{
                if(res.respCode == 'AAAAAA'){
                    this.$notify.success("保存成功!");
                } else {
                    this.$notify.error(res.respMsg);
                }
                // 关闭弹框
                this.cancelDialog();
                this.loadingSavStatus = false;
            })
            .catch((err)=>{
                this.loadingSavStatus = false;
                this.$notify.error(err.respMsg);
            });
        } else {
          Utils.formValidateTips(this.$refs.dialogForm.fields)
        }
      })
    },
      
  }
}
</script>
<style lang="less" scoped>
.currentPage{
	.el-table--enable-row-hover  {
		.el-table__body {
			tr:hover>td {
				background-color: #c694dc !important;
			}
		}
	}
}
::v-deep .save-dialog.el-dialog {
  height: 60vh!important;
}
</style>