<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="'userBusiness: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="6" :sm="8">
            <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.userName"></a-input>
            </a-form-item>
          </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="身份证号">
                <a-input placeholder="请输入身份证号" :maxlength="18" v-model="queryParam.idcardNumber"></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 -->
    <p >* 本页面涉及到的纳税金额仅作参考,实际以缴纳至税务局的纳税额为准</p>
    <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;display: flex;flex-direction: row">
      <div style="display: flex;flex-direction: column"><i class="anticon anticon-info-circle ant-alert-icon"></i>总人数<a style="font-weight: 600">{{ sumPerson}}人</a></div>

      <div style="display: flex;flex-direction: column;margin-left: 20%;"><i class="anticon anticon-info-circle ant-alert-icon"></i> 总接单数 <a style="font-weight: 600">{{ sumOrderNum}}单</a></div>

      <div style="display: flex;flex-direction: column;margin-left: 20%;"><i class="anticon anticon-info-circle ant-alert-icon"></i> 收入总额（不含税）合计 <a style="font-weight: 600">{{ sumNetPayment}}元</a></div>

      <div style="display: flex;flex-direction: column;margin-left: 20%;"><i class="anticon anticon-info-circle ant-alert-icon"></i> 总纳税金额 <a style="font-weight: 600">{{ sumTaxFee}}元</a></div>
    </div>


    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExportXls1('发票信息表')" v-has="'userBusiness: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="businessDetails(record)" v-has="'userBusiness:businessInfo'">业务明细</a>
        </span>

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


        <span slot="action2" slot-scope="text, record">
           <a style="color:#000c17">{{record.idcardNumber}}
             <a-icon type="picture" :style="{color:'#8e8e8e'}" title="身份证照片" @click="viewIdcardPicture(record)" style="margin-left: 12px" />
           </a>
        </span>

      </a-table>
    </div>

<hlw-business-details-list ref="businessDetailsForm" @ok="modalFormOk"></hlw-business-details-list>
    <subcontractor-select-window ref="subcontractorWindow" @ok="modalFormOk"></subcontractor-select-window>
    <hlw-user-info-modal ref="modalForm" @ok="modalFormOk"></hlw-user-info-modal>
    <hlw-picture-modal ref="hwViewPictureForm" @ok="modalFormOk"></hlw-picture-modal>
  </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 HlwBusinessDetailsList from './HlwBusinessDetailsList'
  import SubcontractorSelectWindow from '../hlwsubcontractor/modules/SubcontractorSelectWindow'
  import HlwUserInfoModal from './modules/hlwUserInfoModal'
  import HlwPictureModal from './modules/HlwPictureModal'
  import { USER_AUTH,SYS_BUTTON_AUTH } from "@/store/mutation-types"


  export default {
    name: "HlwUserBusinessInfoList",
    mixins:[JeecgListMixin],
    components: {
      HlwPictureModal,
      HlwUserInfoModal,
      SubcontractorSelectWindow,
      HlwBusinessDetailsList

    },
    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:[],
        sumNetPayment:0.00,
        sumTaxFee:0.00,
        sumPerson:0,
        sumOrderNum:0,
        description: '自由职业者',
        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: 'userName',
            scopedSlots: { customRender: 'action1' },
          },
          {
            title:'手机号',
            align:"center",
            dataIndex: 'phone',
          },
          {
            title:'身份证号',
            align:"center",
            dataIndex: 'idcardNumber',
          scopedSlots: { customRender: 'action2' }
          },
          {
            title:'接单数',
            align:"center",
            dataIndex: 'paymentNumber',
            sorter: true
          },
          {
            title:'收入总额（不含税）',
            align:"center",
            dataIndex: 'personalNetPayment',
            sorter: true
          },
          {
            title:'纳税总额',
            align:"center",
            dataIndex: 'personalTaxFee',
            sorter: true
          },

          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            // fixed:"right",
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          list: "/wisdom/hlwPaymentDetail/userBusinessInfoList",
          exportXlsUrl: "/wisdom/hlwPaymentDetail/exportBusinessUserInfo",
          getIdcardPicture:"/wisdom/hlwUser/getIdcardPicture",
        },
        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.sumTaxFee=this.returnFloat(res.result.records[0].sumTaxFee)
              this.sumPerson=res.result.records[0].sumPerson
              this.sumOrderNum=res.result.records[0].sumOrderNum
            }else{
              this.sumNetPayment=this.returnFloat(0)
              this.sumTaxFee=this.returnFloat(0)
              this.sumPerson=0
              this.sumOrderNum=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;
        }
      },
      businessDetails(record){
        var params=this.getQueryParams()//查询条件
        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 == 'userBusiness:selectSub') {
            bo=true
            break;
          }
        }
        if(bo){
          record.subcontractorId=params.subcontractorId
        }
        this.$refs.businessDetailsForm.edit(record)
        this.$refs.businessDetailsForm.title = '业务明细'
        this.$refs.businessDetailsForm.disableSubmit = false
      },
      handleExportXls1(){
        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]), this.description+'.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', this.description+'.xls')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link); //下载完成移除元素
            window.URL.revokeObjectURL(url); //释放掉blob对象
          }
        })
      },
      modalFormOk(){
        this.loadData(1)
      },

      //搜索服务商
      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);
      },


      viewIdcardPicture(record){
        getAction(this.url.getIdcardPicture, {idcardNumber: record.idcardNumber}).then((res) => {
          if (res.success) {
            if(res.result){
              if( res.result.idcardPicture){
                var idcardPicture = res.result.idcardPicture
                var idcard = [];
                var arr=idcardPicture.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>