<template>
  <div class="page-header-index-wide">
    <a-card :bordered="false">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <a-row :gutter="24">

            <a-col :md="6" :sm="8" v-has="'companyBusiness:selectSub'">
              <a-spin :spinning="confirmLoading">
                <a-form :form="form">
                  <a-form-item label="服务商" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <template v-if="!model.id">
                      <a-input-search
                        placeholder="选择服务商"
                        readOnly
                        v-decorator="[ 'hlwSubcontractorName', {}]"
                        @search="onSearch">
                        <a-button slot="enterButton" icon="search" v-if="!model.id">选择</a-button>
                      </a-input-search>
                    </template>
                  </a-form-item>
                </a-form>
              </a-spin>
            </a-col>


            <a-col :md="8" :sm="10">
              <a-form-item label="统计月份">
                <a-range-picker
                  style="width: 100%"
                  v-model="queryParam.paymentResultTimeRange"
                  format="YYYY-MM-DD"
                  :placeholder="['开始时间', '结束时间']"
                  @change="onDateChange"
                  @ok="onDateOk"
                  :allowClear="allowClear"
                />
              </a-form-item>
            </a-col>


            <a-col :md="6" :sm="8">
              <a-form-item label="商户名称">
                <a-input placeholder="请输入商户名称" v-model="queryParam.companyName"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="税号">
                <a-input placeholder="请输入税号" v-model="queryParam.dutyParagraph"></a-input>
              </a-form-item>
            </a-col>



            <a-col :md="6" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <!--<a @click="handleToggleSearch" style="margin-left: 8px">-->
              <!--{{ toggleSearchStatus ? '收起' : '展开' }}-->
              <!--<a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>-->
              <!--</a>-->
            </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 查询区域-END -->

      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <a-row :gutter="24">
          <a-col :md="6" :sm="6">
            <div style="display: flex;flex-direction: column">
              <span style="font-weight: 600;color: #2eabff;">总商户数</span>
              <span style="font-weight: 600;margin-top: 5px;">{{ sumCompanyNumber}}</span>
            </div>
          </a-col>
          <a-col :md="6" :sm="6">
            <div style="display: flex;flex-direction: column">
              <span style="font-weight: 600;color: #2eabff;">总发单数</span>
              <span style="font-weight: 600;margin-top: 5px;">{{ sumPaymentNumber}}</span>
            </div>
          </a-col>
          <a-col :md="6" :sm="6">
            <div style="display: flex;flex-direction: column">
              <span style="font-weight: 600;color: #2eabff;">总开票额</span>
              <span style="font-weight: 600;margin-top: 5px;">{{ sumNetPayment}}元</span>
            </div>
          </a-col>
          <a-col :md="6" :sm="6">
            <div style="display: flex;flex-direction: column">
              <span style="font-weight: 600;color: #2eabff;">总纳税额</span>
              <span style="font-weight: 600;margin-top: 5px;">{{ sumTaxPayment}}元</span>
            </div>
          </a-col>
        </a-row>
      </div>

      <!-- 操作按钮区域 -->
      <div class="table-operator">
        <a-button type="primary" icon="download" @click="handleExportXls('合作商户')" v-has="'companyBusiness:export'">导出</a-button>
      </div>

      <!-- table区域-begin -->
      <div>
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :loading="loading"
          @change="handleTableChange">

        <span slot="action" slot-scope="text, record">
          <a @click="viewBusinessDetail(record)"  v-has="'companyBusiness:businessInfo'">业务明细</a>
          <a-divider type="vertical"  v-has="'companyBusiness:invoiceInfo'" />
            <a @click="viewBusinessInvoiceDetail(record)"  v-has="'companyBusiness:invoiceInfo'">发票明细</a>
        </span>

          <span slot="action1" slot-scope="text, record">
           <a @click="handleDetail(record)">{{text}}</a>
        </span>


          <span slot="action2" slot-scope="text, record">
           <a style="color:#000c17">{{record.dutyParagraph}}
             <a-icon type="picture" :style="{color:'#8e8e8e'}" title="营业执照" @click="viewBusinessLicense(record)" style="margin-left: 12px" />
           </a>
        </span>
        </a-table>
      </div>
     <hlw-company-business-modal ref="modalForm" @ok="modalFormOk"></hlw-company-business-modal>
      <subcontractor-select-window ref="subcontractorWindow" @ok="modalFormOk"></subcontractor-select-window>
      <hlw-company-business-details-list ref="companyBusinessDetailsForm" @ok="modalFormOk"></hlw-company-business-details-list>
      <hlw-picture-modal ref="hwViewPictureForm" @ok="modalFormOk"></hlw-picture-modal>
      <hlw-company-business-invoice-details-list  ref="companyBusinessInvoiceDetailsForm" @ok="modalFormOk"></hlw-company-business-invoice-details-list>
    </a-card>
  </div>
</template>

<script>

  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { filterObj } from '@/utils/util';
  import { getAction,postAction,deleteAction,downFile } from '@/api/manage'
  import moment from "moment"
  import HlwCompanyBusinessModal from './modules/HlwCompanyBusinessModal'
  import SubcontractorSelectWindow from '../hlwsubcontractor/modules/SubcontractorSelectWindow'
  import HlwCompanyBusinessDetailsList from './HlwCompanyBusinessDetailsList'
  import HlwPictureModal from './modules/HlwPictureModal'
  import { USER_AUTH,SYS_BUTTON_AUTH } from "@/store/mutation-types"
  import HlwCompanyBusinessInvoiceDetailsList from './HlwCompanyBusinessInvoiceDetailsList'


  export default {
    name: "HlwCompanyBusinessList",
    mixins:[JeecgListMixin],
    components: {
      HlwCompanyBusinessInvoiceDetailsList,
      HlwPictureModal,
      HlwCompanyBusinessDetailsList,
      SubcontractorSelectWindow,
      HlwCompanyBusinessModal
    },
    data () {
      return {
        model: {},
        confirmLoading: false,
        form: this.$form.createForm(this),
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        selectedDepartKeys:[], //保存用户选择服务商id
        checkedDepartKeys:[],
        sumCompanyNumber: 0,//总商户数
        sumPaymentNumber: 0,//总发单数
        sumNetPayment: 0.00,//总开票额
        sumTaxPayment: 0.00,//总纳税额
        description: 'hw_userinfo管理页面',
        allowClear:false,
        // 查询条件
        queryParam: {
          paymentResultTimeRange:[moment(new Date(new Date().getFullYear(),new Date().getMonth(),1), 'YYYY/MM/DD'), moment(new Date(), 'YYYY/MM/DD')],
          paymentResultTime_begin:new Date(new Date().getFullYear(),new Date().getMonth(),1).toLocaleDateString()+" 00:00:00",
          paymentResultTime_end:new Date().toLocaleDateString() +" 23:59:59",
        },
        /* 排序参数 */
        isorter:{
          column: '',
          order: '',
        },
        // 表头
        columns: [
          {
            title:'商户名称',
            align:"center",
            dataIndex: 'companyName',
            scopedSlots: { customRender: 'action1' },
          },
          {
            title:'税号',
            align:"center",
            dataIndex: 'dutyParagraph',
            scopedSlots: { customRender: 'action2' }
          },
          {
            title:'所在地',
            align:"center",
            dataIndex: 'provinceCityCountry'
          },
          {
            title:'发单数',
            align:"center",
            dataIndex: 'paymentNumber',
            sorter: true
          },
          {
            title:'开票总额',
            align:"center",
            dataIndex: 'personalNetPayment',
            sorter: true
          },
          {
            title:'纳税总额',
            align:"center",
            dataIndex: 'personalTaxPayment'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            scopedSlots: { customRender: 'action' },
          }
        ],
        url: {
          list: "/wisdom/hlwSubcontractorAccountFlow/companyBusinessList",
          exportXlsUrl: "/wisdom/hlwSubcontractorAccountFlow/exportBusinessCompany",
          getBusinessLicense: "/wisdom/hlwPayment/getBusinessLicense",
        },
        dictOptions:{
        }
      }
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.exportXlsUrl}`;
      }
    },
    methods: {
      getQueryParams(){
        console.log(this.queryParam.paymentResultTimeRange)
        var param = Object.assign({}, this.queryParam,this.isorter);
        param.field = this.getQueryField();
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        param.subcontractorId=this.checkedDepartKeys[0]
        delete param.paymentResultTimeRange; // 时间参数不传递后台
        return filterObj(param);
      },
      initDictConfig(){
      },
      onDateChange: function (value, dateString) {
        console.log(dateString[0],dateString[1]);
        this.queryParam.paymentResultTime_begin=dateString[0]+" 00:00:00";
        this.queryParam.paymentResultTime_end=dateString[1] +" 23:59:59";
      },
      onDateOk(value) {
        console.log(value);
      },

      loadData(arg) {
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        if(arg){
          this.ipagination.current=arg
        }
        var params = this.getQueryParams()//查询条件
        this.loading = true
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = res.result.records
            this.ipagination.total = res.result.total;
            if( res.result.records.length > 0){
              this.sumNetPayment = this.returnFloat(res.result.records[0].sumNetPayment);
              this.sumCompanyNumber = res.result.records[0].sumCompanyNumber;
              this.sumPaymentNumber = res.result.records[0].sumPaymentNumber;
              this.sumTaxPayment = this.returnFloat(res.result.records[0].sumTaxPayment);
            }else{
              this.sumNetPayment = this.returnFloat(0);
              this.sumTaxPayment = this.returnFloat(0);
              this.sumCompanyNumber = 0;
              this.sumPaymentNumber = 0;
            }
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
      },

      returnFloat(value){
        var value=Math.round(parseFloat(value)*100)/100;
        var s=value.toString().split(".");
        if(s.length==1){
          value=value.toString()+".00";
          return value;
        }
        if(s.length>1){
          if(s[1].length<2){
            value=value.toString()+"0";
          }
          return value;
        }
      },

      handleExportXls(fileName){
        if(!fileName || typeof fileName != "string"){
          fileName = "合作商户"
        }
        let param = this.getQueryParams()//查询条件
        downFile(this.url.exportXlsUrl,param).then((data)=>{
          if (!data) {
            this.$message.warning("文件下载失败")
            return
          }
          if (typeof window.navigator.msSaveBlob !== 'undefined') {
            window.navigator.msSaveBlob(new Blob([data]), fileName+'.xls')
          }else{
            let url = window.URL.createObjectURL(new Blob([data]))
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName+'.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link); //下载完成移除元素
            window.URL.revokeObjectURL(url); //释放掉blob对象
          }
        })
      },


      //搜索服务商
      onSearch(){
        this.$refs.subcontractorWindow.add(this.checkedDepartKeys);
      },
      // 获取用户选择服务商弹提交的返回数据
      modalFormOk (formData) {
        this.selectedDepartKeys = [];
        for (let i = 0; i < formData.departIdList.length; i++) {
          this.selectedDepartKeys.push(formData.departIdList[i].key);
          this.form.setFieldsValue({ hlwSubcontractorName: formData.departIdList[i].title })
        }
        this.checkedDepartKeys = this.selectedDepartKeys  //更新当前的选择keys

      },
      // 重置
      searchReset(){
        this.selectedDepartKeys = [];
        this.checkedDepartKeys = [];
        var that = this;
        that.queryParam = {}; //清空查询区域参数
        this.form.setFieldsValue({ hlwSubcontractorName: null})
        that.loadData(this.ipagination.current);
      },

      viewBusinessDetail(record){
        record.paymentResultTime_begin=this.queryParam.paymentResultTime_begin
        record.paymentResultTime_end=this.queryParam.paymentResultTime_end
        var bo=false;
        //获取页面权限
        let authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || "[]");
        for (var auth of authList) {
          if(auth.action == 'companyBusiness:selectSub') {
            bo=true
            break;
          }
        }
        if(bo){
          record.subcontractorId=this.checkedDepartKeys[0]
        }
        console.log(11111, record.subcontractorId)
        this.$refs.companyBusinessDetailsForm.edit(record)
        this.$refs.companyBusinessDetailsForm.title = '业务明细'
        this.$refs.companyBusinessDetailsForm.disableSubmit = false
      },



      viewBusinessInvoiceDetail(record){
        record.paymentResultTime_begin=this.queryParam.paymentResultTime_begin
        record.paymentResultTime_end=this.queryParam.paymentResultTime_end
        var bo=false;
        //获取页面权限
        let authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || "[]");
        for (var auth of authList) {
          if(auth.action == 'companyBusiness:selectSub') {
            bo=true
            break;
          }
        }
        if(bo){
          record.subcontractorId=this.checkedDepartKeys[0]
        }
        this.$refs.companyBusinessInvoiceDetailsForm.edit(record)
        this.$refs.companyBusinessInvoiceDetailsForm.title = '发票明细'
        this.$refs.companyBusinessInvoiceDetailsForm.disableSubmit = false
      },


      viewBusinessLicense(record){
        getAction(this.url.getBusinessLicense, {isThroughPlatform: record.isThroughPlatform,companyId:record.companyId}).then((res) => {
          if (res.success) {
            if(res.result){
              if(res.result.businessLicense){
                var businessLicense = res.result.businessLicense
                var idcard = [];
                var arr=businessLicense.split(",")
                for (let i = 0; i <arr.length ; i++) {
                  if( arr[i].indexOf("http")!=-1){
                    idcard.push(arr[i])
                  }else{
                    idcard.push(res.result.filePathPrefix  +arr[i])
                  }
                }
                this.$refs.hwViewPictureForm.edit(idcard);
                this.$refs.hwViewPictureForm.title = '营业执照'
                this.$refs.hwViewPictureForm.disableSubmit = false
              }else{
                this.$message.warning('未上传营业执照')
              }
            }else{
              this.$message.warning('未上传营业执照')
            }
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
        })
      }



    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>