<template>
  <div style="padding-bottom:20px;">

      <el-form ref="temp" :rules="create.rules" :model="create.temp" label-position="right" label-width="150px" style="width: 90%;margin:0 auto 50px">

            <h3>基本信息</h3>
            <el-row>
              <el-col :span="8">
                <el-form-item label="创建人：" prop="createrName">
                  <el-input ref="createrName" v-model="create.temp.createrName" class="filter-item" style="width: 100%;"  disabled  />
                </el-form-item>

                <el-form-item label="所属集团：" prop="groupName">
                  <el-input ref="groupName" v-model="create.temp.groupName" class="filter-item" style="width: 100%;"  disabled  />
                </el-form-item>

                <el-form-item label="经销商" prop="dealerName">
                  <el-input ref="dealerName" v-model="create.temp.dealerName" class="filter-item" style="width: 100%;"  disabled  />
                </el-form-item>


                <el-form-item label="备注：" prop="remark">
                  <el-input ref="remark" v-model="create.temp.remark" type="textarea" :autosize="{ minRows: 1.3, maxRows: 4}"  maxlength="255" class="filter-item" style="width: 100%;"  disabled  />
                </el-form-item>

              </el-col>

              <el-col :span="8">
                <el-form-item label="创建时间：" prop="createrDate">
                  <el-input ref="createrDate" v-model="create.temp.createrDate" class="filter-item" style="width: 100%;"     disabled  />
                </el-form-item>

                <el-form-item label="客户名称：" prop="customerName">
                  <el-input ref="customerName" v-model="create.temp.customerName" class="filter-item" style="width: 100%;"     disabled  />
                </el-form-item>
                <el-form-item label="合同开始时间：" prop="contractBeginDate">
                  <el-input ref="contractBeginDate" v-model="create.temp.contractBeginDate" class="filter-item" style="width: 100%;"  disabled  />
                </el-form-item>

                <el-form-item label="合同结束时间：" prop="contractEndDate">
                  <el-input ref="contractEndDate" v-model="create.temp.contractEndDate" class="filter-item" style="width: 100%;"     disabled  />
                </el-form-item>


              </el-col>

              <el-col :span="8">
                <el-form-item label="营业执照：" prop="businessLicense">
                  <el-image style="width: 150px; height: 150px;display:inline-block"  :src="create.temp.picname1" @click="show_pic1()">
                    <!-- <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline" style="font-size:140px"></i>
                    </div>     -->
                  </el-image>
                  <el-dialog :visible.sync="imageIsShow" append-to-body width="40%">
                              <img width="80%" :src="create.temp.picname1" alt="">
                  </el-dialog>

                </el-form-item>
              </el-col>
            </el-row>

            <h3>款项信息</h3>
            <el-row>
              <el-col :span="8">
                <el-form-item label="款项分期：" prop="moneyStep">
                  <el-input ref="moneyStep" v-model="create.temp.moneyStep" class="filter-item" style="width: 100%;"     disabled  />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                  <el-form-item label="合同金额（元）：" prop="contractMoney">
                      <el-input ref="contractMoney" v-model="create.temp.contractMoney" class="filter-item" style="width: 100%;"   disabled  />
                  </el-form-item>
              </el-col>
              <el-col :span="8">
                  <el-form-item label="技术服务费：" prop="serviceCost">
                      <el-input ref="serviceCost" v-model="create.temp.serviceCost" class="filter-item" style="width: 100%;"   disabled  />
                  </el-form-item>
              </el-col>
            </el-row>

            <el-row>
                    <el-table  :data="tableStagesList" border fit highlight-current-row style="width: 100%;" :row-style="rowStyle" :cell-style="cellStyle" class="elTable table-fixed">


                      <el-table-column label="期数" min-width="110px" align="center">
                        <template slot-scope="scope">
                          <span>{{ scope.row.stages }}期</span>
                        </template>
                      </el-table-column>

                      <el-table-column label="应收金额占比" min-width="110px" align="center">
                        <template slot-scope="scope">
                          <span>{{ scope.row.planCostRate }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="应收金额（元）" min-width="110px" align="center">
                        <template slot-scope="scope">
                          <span>{{ scope.row.planCost }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="收款时间" min-width="110px" align="center">
                        <template slot-scope="scope">
                          <span>{{ scope.row.collectionDate}}</span>
                        </template>
                      </el-table-column>


                    </el-table>
            </el-row>

            <h3>货物信息</h3>
            <el-row>

              <el-row>
                    <el-table :data="tableStockList" border fit highlight-current-row style="width: 100%;" :row-style="rowStyle" :cell-style="cellStyle" class="elTable table-fixed">

                      <el-table-column label="序号" align="center" type="index" width="50px">
                        <template slot-scope="scope">
                          <span>{{ scope.$index + 1 }}</span>
                        </template>
                      </el-table-column>

                      <el-table-column label="货品名称" min-width="110px" align="center">
                        <template slot-scope="scope">
                          <span>{{ scope.row.productsName }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="型号" min-width="110px" align="center">
                        <template slot-scope="scope">
                          <span>{{ scope.row.model }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="规格" min-width="110px" align="center">
                        <template slot-scope="scope">
                          <span>{{ scope.row.Specifications }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="数量" min-width="110px" align="center">
                        <template slot-scope="scope">
                          <span >{{ scope.row.nums }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="单价(元)" min-width="110px" align="center">
                              <template slot-scope="scope">
                                <span>{{ scope.row.price }}</span>
                              </template>
                      </el-table-column>
                      <el-table-column label="成交价(元)" min-width="110px" align="center">
                              <template slot-scope="scope">
                                <span>{{ scope.row.closingPrice  }}</span>
                              </template>
                      </el-table-column>
                      <el-table-column label="总价(元)" min-width="110px" align="center">
                              <template slot-scope="scope">
                                <span>{{ scope.row.sumPrice  }}</span>
                              </template>
                      </el-table-column>

                      <el-table-column label="备注" min-width="280px" align="center">
                        <template slot-scope="scope">
                          <span >{{ scope.row.remark }}</span>
                        </template>
                      </el-table-column>
                    </el-table>
              </el-row>

              <el-row type="flex" justify="end">
                    <el-col style="color:#FF4949" :span="6" :offset="18">列表货物总价：{{stockSumPrice}}</el-col>
              </el-row>
              <el-divider></el-divider>


            </el-row>

            <h3>合同附件</h3>
            <el-row>
              <span @click="form_down2()"  style = "color:#409EFF; cursor: pointer;">{{create.temp.applyFileName}}</span>
              <el-button v-if="create.temp.applyFileName  " class="miniSuccess"   @click="form_look2()">在线预览</el-button>

            </el-row>


            <h3>备案信息</h3>
            <el-row>
              <span @click="form_down()"  style = "color:#409EFF; cursor: pointer;">{{create.temp.fileName}}</span>
              <el-button v-if="create.temp.fileName  " class="miniSuccess"   @click="form_look()">在线预览</el-button>
            </el-row>

            <h3>发票信息</h3>
            <el-row>

              <el-col :span="6"  v-for="(item,index) in tableInvocieList ">
                  <el-col :span="24">
                    <el-image style="width: 150px; height: 150px;display:inline-block"  :src="item.picname"></el-image>
                  </el-col>
                  <el-col :span="24">
                    寄出时间：{{item.postDate}}
                  </el-col>
               </el-col>


            </el-row>


            <h3>流程进度</h3>
            <el-row>

              <el-steps :active="active" align-center finish-status="success">
                <el-step
                  v-for="(item,index) in activeList"
                  :key="index"
                  :title="item.stepName"
                  :status="item.status"
                >
                  <template slot="description">
                    <div class="step-row">
                      <div>{{ item.employeeName }}&nbsp;&nbsp;{{ item.resumeTime }}</div>
                      <div>{{ item.remark }}</div>
                    </div>
                  </template>
                </el-step>
              </el-steps>


            </el-row>

          </el-form>
          <!-- PDF预览 -->
          <el-dialog title="在线预览" :visible.sync="dialogVisible4" width="96%"  append-to-body center>
            <!-- <pdf v-for="item in numPages" :key="item" :src="pdfSrc" :page="item" ref="pdf"></pdf> -->
              <!-- <iframe :src="pdfSrc" frameborder="0" style="width: 100%; height: 600px"></iframe> -->

                <iframe :src="pdfSrc" ref="myIframe" frameborder="0" width="100%" height="1200px">

                </iframe>
          </el-dialog>


  </div>
  </template>
  <script>


  import { GetDataByName, PostDataByName, failproccess, ExecDataByConfig, GetDataByNames, checkButtons, calculativeWidth , downloadfileCRM} from '@/api/common'
  import Cookies from 'js-cookie'
  import { parseTime } from '@/utils/index.js'
  import Pagination from '@/components/Pagination'
  import { MessageBox } from 'element-ui'
  import { getToken } from '@/utils/auth'
import { constants } from 'zlib';
import mammoth from "mammoth";

  export default {
    components: {  mammoth  },
    name: 'ContractMoreDetail',
    props: {
      conmoreData: {
        type: Object,
        required: true
      }
    },


    data() {
      return {
        htmlContent: null,
        create: {

          temp: {  contractStatus: '',    customerId: '', groupId: '', groupName: '', serviceCode: '', contractBeginDate: parseTime(new Date(), '{y}-{m}-{d}'), contractEndDate: parseTime(new Date(), '{y}-{m}-{d}'), createrId:  Cookies.get('employeid'), createrName:  Cookies.get('employename'),moneyStep: '1',contractMoney: '', businessLicense: -1,picname1: ''},
          // 客户名称
          getdataListParmCust: {
            name: 'getCustomerByGroupId',
            returntype: 'Map',
            parammaps: { groupId: "" }
          },
          customerNameList:[],

          // 款项信息 - 表格
          getdataListParmStages: {
            name: 'getContractCost',
            returntype: 'Map',
            parammaps: { id: "" }
          },
          // 货物信息 - 表格
          getdataListParmStock: {
            name: 'getContractGoodsByCid2',
            returntype: 'Map',
            parammaps: { id: "" }
          }
        },
         //款项期数表格
        tableStagesList:[],
        //备货表格
        tableStockList:[],
        //发票信息
        tableInvocieList :[],
        stockSumPrice:0,

        dialogImageUrl: '',
        imageIsShow: false,
        dialogImageUrl2: '',
        imageIsShow2: false,

        dialogVisible4: false,
        pdfSrc: '',
        numPages: null,

        requestParam: {},
        isokDisable: false,

        rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
        cellStyle: { padding: 0 + 'px' },

        activeList: [
          // { title: '合同录入', date: 1, name: 21 }, { title: '办公室主任审核', date: 3 }, { title: '设备中心审核', date: 1, name: 3, status: 'error', reason: 3 }
        ],
        active: 1


      }
    },
   watch: {
      conmoreData: {
        deep: true,
        handler: function (item) {
          console.log("父组件：", item)


          this.get_info_list()
          this.getStagesTableList()
          this.getStockTableList()

          this.getInvocieList()
          this.getResumeLineList()

        }
      },

      tableStockList: {
        deep: true,
        handler: function (item) {
            //计算总价格
            var sum = 0
            this.tableStockList.forEach(function(i){
                sum = parseInt(i.nums) * parseFloat(i.closingPrice) + sum
            })
            this.stockSumPrice = sum

        }
      },

    },
    mounted() {

    },


    created() {
       this.get_info_list()
       this.getStagesTableList()
       this.getStockTableList()
       this.getInvocieList()
       this.getResumeLineList()


    },
    beforeDestroy() {

    },
    methods: {

 //AJAX事件 - 流程信息
      getResumeLineList() {

        var me = this
        var send_data = {
            name: 'getContractResumeLine',
            parammaps: {
              id:this.conmoreData.id,
            }
       }
        GetDataByName(send_data).then(response => {
          console.log('流程信息============', response )
          if (response.data.list !== null) {

            if(response.data.list.length != 0){

              var processNum = response.data.list[0].processNum
              var arrList = response.data.list

              var activeList = []


              for (var i=0; i< processNum;i++){
                 activeList.push({ employeeName: '', resumeTime:'', stepName: '', status: '' , remark: ''  })
              }

              arrList.forEach(function(item,index){
                 activeList[index].stepName = item.stepName
                 activeList[index].employeeName = item.employeeName
                 activeList[index].resumeTime = item.resumeTime
                  if(item.statusName == 0){
                      activeList[index].remark = item.remark
                      activeList[index].status =  'error'
                  }
              })


              //过滤出没有名字的，代表激活当前流程
              let arr1 = arrList.map((value, index) => index).filter(index => arrList[index].employeeName == "");

              console.log(arr1);  // 输出: [1, 3, 5, 7, 8]
              //取第一个没有名字的索引
              if(arr1.length !== 0 ){
                me.active = arr1[0]
              }


              arrList.forEach(function(item,index){
                  //如果是最后一个内容，且有名字，激活的是最后
                  if(item.employeeName !== "" && (index  == processNum-1 )){
                    me.active = processNum
                    console.log(processNum)
                  }
               })


              me.activeList = activeList

            }else{
               me.activeList = []
               me.active = 0

            }

          } else {
            me.activeList = []
               me.active = 0
          }
        })
      },

      //AJAX事件 - 获取基本信息
      get_info_list() {
        var send_data = {
            name: 'getContractApplicationById',
            parammaps: {
              id:this.conmoreData.id,
            }
       }
        GetDataByName(send_data).then(response => {
          console.log('获取基本信息数据', response )
          if (response.data.list !== null) {
             this.create.temp = response.data.list[0]
             this.create.temp.picname1 =  process.env.VUE_APP_BASE_API + this.create.temp.picname1
          } else {
             this.create.temp ={}
          }
        })
      },


       // 款项信息表格
      getStagesTableList() {

        var send_data = {
            name: 'getContractCost',
            parammaps: {
              id:this.conmoreData.id,
            }
         }
        GetDataByName(send_data).then(response => {
          if (response.data.list !== null) {
            this.tableStagesList   = response.data.list
            console.log('款项信息表格数据', response.data.list)
          } else {
            this.tableStagesList = []
          }
        })
      },

      // 备货信息表格
      getStockTableList() {

         var send_data = {
            name: 'getContractGoodsByCid2',
            parammaps: {
              id:this.conmoreData.id,
            }
         }
        GetDataByName(send_data).then(response => {
          if (response.data.list !== null) {
            this.tableStockList  = response.data.list
            console.log('备货信息表格数据', response.data.list)
          } else {
            this.tableStockList  = []
          }
        })
      },

      //图片展示
      show_pic1() {
        this.imageIsShow = true
      },
      // 发票信息
      getInvocieList() {

         var send_data = {
            name: 'getContractInvoice',
            parammaps: {
              id:this.conmoreData.id,
            }
         }
        GetDataByName(send_data).then(response => {
          if (response.data.list !== null) {
            for (let i = 0; i < response.data.list.length; i++) {
              var url = process.env.VUE_APP_BASE_API + response.data.list[i].picname
              this.$set(response.data.list[i], 'picname', url )
            }

            this.tableInvocieList  = response.data.list
            console.log('发票信息表格数据', response.data.list)
          } else {
            this.tableInvocieList  = []
          }
        })
      },

      form_down(){

        var send_data = {
            fileId: this.create.temp.fileId
         }


         var fileName = this.create.temp.fileName

        downloadfileCRM(send_data).then(res => {


          const content = res
          const blob = new Blob([content])

          if ('download' in document.createElement('a')) { // 非IE下载
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else { // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
        })

      },


      form_look(){

        var me = this
        me.pdfSrc = ""
        var  typeStr = me.create.temp.fileName
        var url = process.env.VUE_APP_BASE_API + 'viewfileCRM/' + this.create.temp.fileId


        me.dialogVisible4 = true
        me.pdfSrc = url


      },

      form_look2(){

        var me = this
        me.pdfSrc = ""
        var  typeStr = me.create.temp.applyFileName
        var url = process.env.VUE_APP_BASE_API + 'viewfileCRM/' + this.create.temp.applyFileId

        // window.open(url)

        me.dialogVisible4 = true
        me.pdfSrc = url

      //var url = process.env.VUE_APP_BASE_API + 'viewfileCRM/79'
      //  window.open('http://www.leomay.com/upload/file/mmo-20170707165001.pdf')


        // if(typeStr !== ""){
        //   var typeArr = typeStr.split(".")
        //   var type = typeArr[typeArr.length-1]
        //   console.log(type)
        //   if(type == "jpg" || type == "pdf" ){


        //     me.dialogVisible4 = true
        //     me.pdfSrc = url
        //   }
        //   //Word 文件
        //   if(type == "docx" || type == "doc" ){
        //     me.dialogVisible4 = true
        //     fetch(url)
        //       .then(response => response.blob()) // 将响应转换为Blob对象
        //       .then(blob => {
        //         console.log(blob)
        //         // 使用mammoth.js将Blob转换为HTML
        //         mammoth.convertToHtml({ arrayBuffer: blob })
        //           .then((result) => {

        //             // 获取iframe元素
        //             var iframe = me.$refs.myIframe;
        //              // 设置iframe中的HTML内容
        //             var contentWindow = iframe.contentWindow;
        //             contentWindow.document.open("text/html", "replace");
        //             contentWindow.document.write(result.value);
        //             contentWindow.document.close();


        //           })
        //           .catch((err) => console.error(err));
        //       })
        //       .catch((err) => console.error(err));


        //   }


        // }


      },


      form_down2(){

        var send_data = {
            fileId: this.create.temp.applyFileId
        }


        var fileName = this.create.temp.applyFileName

        downloadfileCRM(send_data).then(res => {


          const content = res
          const blob = new Blob([content])

          if ('download' in document.createElement('a')) { // 非IE下载
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else { // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
        })

        }


    }
  }
  </script>
