<template>
   <div class="content" v-loading="loading" element-loading-text="正在统计，请耐心等待" 
    element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.01)">
       <div class="btn-box">
           <el-button type="success" icon="el-icon-setting" size="mini" @click="countSet">统计设置</el-button>
           <el-button :type="btnDisabled?'':'primary'" :disabled="btnDisabled" size="mini" icon="el-icon-s-data"  @click="count">统计</el-button>
           <el-button :type="btnDisabled?'':'warning'" :disabled="btnDisabled" size="mini" icon="el-icon-edit"  @click="editTable">编辑</el-button>
           <el-button :type="isEditing?'success':''" :disabled="!isEditing" size="mini" icon="el-icon-circle-check"  @click="saveTable">保存</el-button>
           <el-button :type="btnDisabled?'':'primary'" :disabled="btnDisabled" size="mini" icon="el-icon-printer"   @click="print">打印</el-button>
       </div>
       <div class="info-box">
           <h3 class="title">档案室基本情况表</h3>
           <div class="top-info">
              <el-row>
                <el-col :span="3" :offset="17">表号：</el-col>
                <el-col :span="4">DA-3表</el-col>
              </el-row>
              <el-row>
                <el-col :span="3" :offset="17">制定机关：</el-col>
                <el-col :span="4">国家档案局</el-col>
              </el-row> 
              <el-row>
                <el-col :span="4">单位名称：</el-col>
                <el-col :span="13">{{detail.unitName}}</el-col>
                <el-col :span="3">批准机关：</el-col>
                <el-col :span="4">国家统计局</el-col>
              </el-row>
              <el-row>
                <el-col :span="4">单位类别代码：</el-col>
                <el-col :span="13">{{detail.unitCode}}</el-col>
                <el-col :span="3">批准文号：</el-col>
                <el-col :span="4">国统制（2019）8号</el-col>
              </el-row>
              <el-row>
                <el-col :span="4">统一社会信用代码：</el-col>
                <el-col :span="13">20年</el-col>
                <el-col :span="3">有效期至：</el-col>
                <el-col :span="4">2022年1月</el-col>
              </el-row>   
           </div>
           <table-box :tableData="tableData"/>
           <div class="bottom-info">
              <div>单位负责人：{{detail.unitPerson}}</div>
              <div>填表人：{{detail.completed}}</div>
              <div>报出时间：{{detail.outTime}}</div>
           </div>
       </div>
       <dia-count :visible="countVisible"  @cancel="cancel" />
       <dia-pdf :visible="pdfVisible" :pdfUrl="pdfUrl"  @cancel="cancel"/>
   </div>
</template>

<script>
  import tableBox from "./tableBox"
  import { TABLE_DATA } from '../const.js'
  import { editYear, yearCount, getPdf } from "@/api/archives-management/annualReport"
  import { message } from "@/utils/common"
  import _ from "lodash"
  import diaCount from "./diaCount.vue"
  import DiaPdf from "@/components/DiaPdf"
  import { URL_PREFIX } from "@/utils/url-prefix"

  export default {
    props: {
      detail: {
        type: Object,
        default: () => {}
      }
    },
    data(){
        return {
          tableData: _.cloneDeep(TABLE_DATA),
          loading: false,
          countVisible: false, // 统计设置弹框
          pdfVisible: false, // 打印弹框
          pdfUrl: '',
          isEditing: false, // 是否编辑中
        }
    },
    watch: {
      'detail': {
        handler(val, oldVal){
          // 不可编辑状态
          this.changeEditStatus(false);
          if(val.content){
            let content = JSON.parse(val.content)
            this.calTableData(this.tableData,content)
          }else{
            // content为空, 重置表格数据
            this.tableData = _.cloneDeep(TABLE_DATA);
          }
        }
      }
    },
    computed: {
      btnDisabled(){
        return !Object.keys(this.detail).length
      }
    },
    components: {
        tableBox,
        diaCount,
        DiaPdf,
    },
    methods: {
      cancel(){
        this.countVisible = false;
        this.pdfVisible = false;
      },
      countSet(){
        this.countVisible = true;
      },
      count(){
        const params = {
          currentYear: this.detail.year
        }
        this.loading = true
        yearCount(params).then(res => {
          this.loading = false
          if(res.code === '100'){
            message('success', '统计完成', 2000)
            this.countTable(this.tableData,res.body) // 将统计返回的数据填入到数量输入框中
          }
        }).catch(() => {
          this.loading = false
        })
      },
      // 将统计返回的数据填入到数量输入框中
      countTable(data, res){
        data.map(item => {
          if(item.typeId){
            item.quantity = res[item.typeId][item.typeKey]
          }
          if(item.children && item.children.length){
            this.countTable(item.children, res)
          }
        })
      },
      print(){
        let arrList = this.getPrintParams(this.tableData,[])
        getPdf(arrList).then(res => {
          if(res.code === '100'){
            this.pdfVisible = true;
            this.pdfUrl = URL_PREFIX + '/point-strategy/v/ureport/showPdf?fileName=' + res.body.fileName;
          }
        })
      },
      getPrintParams(data, arr){
        data.map(item => {
          let obj = {}
          Object.keys(item).forEach( v => {
            if(v !== 'children'){
              obj[v] = item[v]
            }
          })
          const conObj = {
            title: '档案室基本情况表',
            num: 'DA-3表',
            year: this.detail.year,
            unitName: this.detail.unitName,
            unitCode: this.detail.unitCode,
            unitPerson: this.detail.unitPerson,
            completed: this.detail.completed,
            outTime: this.detail.outTime,
          }
          arr.push({...obj,...conObj})
          if(item.children &&item.children.length){
            this.getPrintParams(item.children, arr)
          }
        })
        return arr
      },
      saveTable(){
        let content =this.getContent(this.tableData, {})
        const params = { ...this.detail, content: JSON.stringify(content) }
        editYear(params).then(res => {
          if(res.code === '100'){
            message('success', '保存成功', 2000)
            // 不可编辑状态
            this.changeEditStatus(false);
            this.$emit('getData')
          }
        })
      },
      // 计算提交的数量输入框值
      getContent(data,obj){
        data.forEach(item => {
          if(item.quantity){
            obj[item.sort] = item.quantity
          }
          if(item.children && item.children.length){
            this.getContent(item.children, obj)
          }
        })
        return obj
      },
      editTable(){
        // 编辑状态
        this.changeEditStatus(true);
      },
      changeEditStatus(flag){
        // 编辑状态
        this.toEditStatus(this.tableData, flag)
        this.isEditing = flag;
      },
      // 将输入框变成编辑状态
      toEditStatus(data, flag){
        return data.map(item => {
          this.$set(item,'editable', flag)
          if(item.children && item.children.length){
            this.toEditStatus(item.children, flag)
          }
        })
      },
      // 将查询到的数量赋值到输入框上
      calTableData(data, content){
        return data.map(item => {
          item.quantity = content[item.sort]
          if(item.children && item.children.length){
            this.calTableData(item.children, content)
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .content{
      .btn-box{
          width: 100%;
          text-align: right;
          margin-top: -10px;
      }
      .info-box{
          .title{
              text-align: center;
              margin: 10px 0 5px;
          }
          .top-info{
              font-size: 14px;
              line-height: 20px;
              margin-bottom: 10px;
              .el-row>.el-col:last-child{
                  text-align: right;
              }
              .el-col{
                min-height: 1px;
              }
          }
          .bottom-info{
              font-size: 14px;
              display: flex;
              justify-content: space-between;
              margin-top: 5px;
          }
      }
  }
</style>