<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">
            <a-form-item label="订单编号">
              <a-input placeholder="请输入订单编号" v-model="queryParam.orderNumber"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="需求单号">
              <a-input placeholder="请输入需求单号" v-model="queryParam.requireCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8">
            <a-form-item label="状态">
              <j-dict-select-tag :triggerChange="false" v-model="queryParam.status" placeholder="请选择状态查询"
                                 dictCode="order_status" v-decorator="['status', {}]"/>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <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.userName"></a-input>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8">
              <a-form-item label="创建时间">
                <a-range-picker
                  style="width: 100%"
                  v-model="queryParam.createTimeRange"
                  format="YYYY-MM-DD"
                  :placeholder="['开始时间', '结束时间']"
                  @change="onDateChange"
                  @ok="onDateOk"
                  :allowClear="allowClear"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8" v-has="'order:contract'">
              <a-form-item label="用户合同">
                <j-dict-select-tag :triggerChange="false" v-model="queryParam.contractStatus" placeholder="请选择用户合同"
                                   dictCode="contract_status" v-decorator="['contractStatus', {}]"/>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="6" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a @click="handleToggleSearch">
                {{ toggleSearchStatus ? '取消' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
              <a-button ghost type='primary' @click="searchQuery" icon="search" style="margin-left: 8px">查询</a-button>
              <a-button ghost type='primary' @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="export" @click="handleExportXls('付款模板')" v-has="'order:exportPay'">导出付款</a-button>
      <!--<span v-has="'order:exportPay'">仅导出服务中的订单</span>-->
      <a-button type="primary" @click="batchConfirmOrder" v-has="'order:batchConfirmOrder'">确认订单</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{
        selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :scroll="{ x: scrollX}"
        class="j-table-force-nowrap"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange,getCheckboxProps:getCheckboxProps}"
        @change="handleTableChange">

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

        <span slot="action" slot-scope="text, record">
          <template v-if="record.status == 0 || record.status == 2">
            <a @click="handleCloseOrder(record)" v-has="'order:close'">关闭订单</a>
          </template>
           <template v-else-if="record.status == 1">
            <a @click="handleOpenOrder(record)" v-has="'order:open'">开启订单</a>
          </template>
          <template v-else-if="record.status == 2">
            <a @click="handleCheckOrder(record)" v-has="'order:check'">验收</a>
          </template>
          <template v-else>
            --
          </template>
        </span>

      </a-table>
    </div>

    <HwOrderCheckModal ref="modalCheckForm" @ok="modalFormOk"></HwOrderCheckModal>
    <HwOrderModal ref='HwOrderModal'></HwOrderModal>
  </a-card>
  </div>
</template>

<script>
  import '@/assets/less/TableExpand.less'
  import { filterObj } from '@/utils/util';
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { getAction, deleteAction, putAction, postAction,downFile,batchAction } from '@/api/manage'
  import HwOrderCheckModal from './modules/HwOrderCheckModal'
  import HwOrderModal from './modules/HwOrderModal'
  import { USER_AUTH,SYS_BUTTON_AUTH } from "@/store/mutation-types"

  const confirmOrder = (params) => putAction('/ordermanager/hwOrder/confirmOrder', params)
  const closeOrder = (params) => putAction('/ordermanager/hwOrder/closeOrder', params)
  const limitOrder = (params) => putAction('/ordermanager/hwOrder/limitOrder', params)
  const againOrder = (params) => putAction('/ordermanager/hwOrder/againOrder', params)
  const batchConfirmOrder = (params) => batchAction('/ordermanager/hwOrder/batchConfirmOrder', params)
  const openOrder = (params) => putAction('/ordermanager/hwOrder/openOrder', params)

  export default {
    name: 'HwOrderList',
    mixins: [JeecgListMixin],
    components: {
      HwOrderCheckModal,
      HwOrderModal
    },
    data() {
      return {
        description: '订单管理页面',
        allowClear:false,
        // 查询条件
        queryParam: {
          createTimeRange:[],
        },
        columns: [],
        // 表头
        defColumns: [
          {
            title: '订单编号',
            align: 'left',
            width: 200,
            dataIndex: 'orderNumber',
            scopedSlots: { customRender: 'action1' }
          },
          {
            title: '需求单号',
            align: 'left',
            width: 200,
            dataIndex: 'requireCode'
          },
          {
            title: '发布企业',
            align: 'left',
            width: 300,
            dataIndex: 'companyName'
          },
          {
            title: '接单人',
            align: 'left',
            width: 150,
            dataIndex: 'userName'
          },
          {
            title: '参考单价',
            align: 'left',
            width: 150,
            dataIndex: 'hwRequirement.price'
          },
          {
            title: '合同状态',
            align: 'left',
            width: 150,
            dataIndex: 'electronicContractStatus',
            customRender: function(value, record) {
              if(record.electronicContractStatus === 2){
                return '已签署';
              }
              return '待签署';
            }
          },
          {
            title: '订单状态',
            align: 'left',
            width: 150,
            dataIndex: 'status_dictText',
            customRender: function(value, record) {
              return value ? value : '--';
            }
          },
          {
            title: '验收进度',
            align: 'left',
            width: 150,
            dataIndex: 'isCheck_dictText'
          },
          {
            title: '用户合同',
            align: 'left',
            width: 150,
            dataIndex: 'workContractType_dictText',
          },
          {
            title: '创建时间',
            align: 'left',
            width: 150,
            dataIndex: 'createTime',
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'left',
            fixed: 'right',
            width: 180,
            scopedSlots: { customRender: 'action' }
          }
        ],
        comColumns: [
          {
            title: '订单编号',
            align: 'left',
            width: 200,
            dataIndex: 'orderNumber',
            scopedSlots: { customRender: 'action1' }
          },
          {
            title: '需求单号',
            align: 'left',
            width: 200,
            dataIndex: 'requireCode'
          },
          {
            title: '发布企业',
            align: 'left',
            width: 300,
            dataIndex: 'companyName'
          },
          {
            title: '接单人',
            align: 'left',
            width: 150,
            dataIndex: 'userName'
          },
          {
            title: '参考单价',
            align: 'left',
            width: 150,
            dataIndex: 'hwRequirement.price'
          },

          {
            title: '合同状态',
            align: 'left',
            width: 150,
            dataIndex: 'electronicContractStatus',
            customRender: function(value, record) {
              if(record.electronicContractStatus === 2){
                return '已签署';
              }
              return '待签署';
            }
          },
          {
            title: '订单状态',
            align: 'left',
            width: 150,
            dataIndex: 'status_dictText',
            customRender: function(value, record) {
              return value ? value : '--';
            }
          },
          {
            title: '验收进度',
            align: 'left',
            width: 150,
            dataIndex: 'isCheck_dictText'
          },
          {
            title: '创建时间',
            align: 'left',
            width: 150,
            dataIndex: 'createTime',
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'left',
            fixed: 'right',
            width: 180,
            scopedSlots: { customRender: 'action' }
          }
        ],
        scrollX: 1930,
        isorter: {
          column: 'updateTime',
          order: 'desc'
        },
        url: {
          list: '/ordermanager/hwOrder/list',
          delete: '/ordermanager/hwOrder/delete',
          deleteBatch: '/ordermanager/hwOrder/deleteBatch',
          exportXlsUrl: '/ordermanager/hwOrder/exportXls',
          importExcelUrl: 'ordermanager/hwOrder/importExcel'
        },
        dictOptions: {}
      }
    },
    computed: {
      importExcelUrl: function() {
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
      }
    },
    created() {
      this.initColumns();
    },
    methods: {
      initColumns(){
        //获取页面权限
        let authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || "[]");
        var bo = false;
        for (var auth of authList) {
          if(auth.action === 'order:contract') {
            bo = true;
            break;
          }
        }
        console.log('bo',bo)
        if (bo) {
          this.columns = this.defColumns;
          this.scrollX = 1930;
        } else {
          this.columns = this.comColumns;
          this.scrollX = 1780;
        }
      },
      getQueryParams(){
        console.log(this.queryParam.createTimeRange)
        var param = Object.assign({}, this.queryParam,this.isorter);
        param.field = this.getQueryField();
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        delete param.createTimeRange; // 时间参数不传递后台
        return filterObj(param);
      },
      initDictConfig() {
      },
      //订单详情页为路由菜单
      handleDetail(record) {
        // this.$router.push({ path: '/ordermanager/hwOrder/edit/' + record.id })
        this.$refs.HwOrderModal.visible = true
        this.$refs.HwOrderModal.code = record.id
        this.$refs.HwOrderModal.initAutoListConfig()
      },
      //确认订单
      handleOkOrder(record) {
        let that = this
        const modal = that.$confirm({
          title: '确认订单',
          closable: true,
          keyboard: false,
          maskClosable: true,
          content: '是否确认订单准确无误？',
          okText: '确认订单',
          cancelText: '取消',
          onOk: function() {
            that.loading = true;
            confirmOrder({ id: record.id }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData(1)
              } else {
                that.$error({
                  title: '确认失败',
                  content: res.message,
                  okText: '确定'
                })
              }
              that.loading = false;
            })
          },
          onCancel(e) {
            modal.destroy()
          }
        })
      },
      //取消订单
      handleCloseOrder(record) {
        let that = this
        const modal = that.$confirm({
          title: '关闭订单',
          closable: true,
          keyboard: false,
          maskClosable: true,
          content: '是否确定关闭订单？',
          okText: '确定关闭',
          cancelText: '取消',
          onOk: function() {
            closeOrder({ id: record.id }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData(1)
              } else {
                that.$message.error(res.message)
              }
            })
          },
          onCancel(e) {
            modal.destroy()
          }
        })
      },


      //开启订单
      handleOpenOrder(record) {
        let that = this
        const modal = that.$confirm({
          title: '开启订单',
          closable: true,
          keyboard: false,
          maskClosable: true,
          content: '是否确定开启订单？',
          okText: '确定开启',
          cancelText: '取消',
          onOk: function() {
            openOrder({ id: record.id }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData(1)
              } else {
                that.$message.error(res.message)
              }
            })
          },
          onCancel(e) {
            modal.destroy()
          }
        })
      },



      //中止订单
      handleLimitOrder(record){
        let that = this
        let content = (<p>是否确定中止订单?<br />订单中止后无法给接单人付款，请确认款项已经结清</p>);
        const modal = that.$confirm({
          title: '中止订单',
          closable: true,
          keyboard: false,
          maskClosable: true,
          content: content,
          okText: '确定中止',
          cancelText: '取消',
          onOk: function() {
            limitOrder({ id: record.id }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData(1)
              } else {
                that.$message.error(res.message)
              }
            })
          },
          onCancel(e) {
            modal.destroy()
          }
        })
      },
      onDateChange: function (value, dateString) {
        console.log(dateString[0],dateString[1]);
        this.queryParam.createTime_begin=dateString[0]+" 00:00:00";
        this.queryParam.createTime_end=dateString[1] +" 23:59:59";
      },
      onDateOk(value) {
        console.log(value);
      },
      //监听checkbox属性
      getCheckboxProps(record) {
        return {
          props: {
            // disabled: record.status !=2,
          }
        }
      },
      //乘法函数，用来得到精确的乘法结果
      accMul(arg1, arg2) {
        var m = 0, s1 = arg1.toString(), s2 = arg2.toString()
        try {
          m += s1.split('.')[1].length
        } catch (e) {
        }
        try {
          m += s2.split('.')[1].length
        } catch (e) {
        }
        return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m)
      },

      //重发合同（电子合同）
      handleAgainContract(record){
        let that = this
        const modal = that.$confirm({
          title: '重发合同',
          closable: true,
          keyboard: false,
          maskClosable: true,
          content: '是否确认重发合同？',
          okText: '重发合同',
          cancelText: '取消',
          onOk: function() {
            againOrder({ id: record.id }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData(1)
              } else {
                that.$error({
                  title: '重发失败',
                  content: res.message,
                  okText: '确定'
                })
              }
            })
          },
          onCancel(e) {
            modal.destroy()
          }
        })
      },
      modalFormOk(){
        this.loadData(1)
      },

      //批量确认订单
      batchConfirmOrder(){
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
          return false;
        }
        var selectionRows = this.selectionRows;
        for(var i = 0;i<selectionRows.length;i++){
          if(selectionRows[i].status !=0){
            this.$error({
              title: '确认失败',
              content: '仅支持待确认的订单',
              okText: '确定'
            })
            return false;
          }
          if(selectionRows[i].workContractType == 1){
            this.$error({
              title: '确认失败',
              content: '仅支持非电子合同的订单',
              okText: '确定'
            })
            return false;
          }
        }
        var ids = "";
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ",";
        }
        var that = this;
        const modal = that.$confirm({
          title: '确认订单',
          closable: true,
          keyboard: false,
          maskClosable: true,
          content: '是否确认订单准确无误？',
          okText: '确认订单',
          cancelText: '取消',
          onOk: function() {
            that.loading = true;
            batchConfirmOrder({ batchIds: ids }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.onClearSelected()
                that.loadData(1)
              } else {
                that.$error({
                  title: '确认失败',
                  content: res.message,
                  okText: '确定'
                })
              }
              that.loading = false;
            })
          },
          onCancel(e) {
            modal.destroy()
          }
        })
      },

      //导出付款模板
      handleExportXls(fileName){
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
          return false;
        }
        var selectionRows = this.selectionRows;
        for(var i = 0;i<selectionRows.length;i++){
          if(selectionRows[i].status !=2){
            this.$error({
              title: '导出失败',
              content: '仅支持导出已确认的订单',
              okText: '确定'
            })
            return false;
          }
        }
        if(!fileName || typeof fileName != "string"){
          fileName = "导出文件"
        }
        let param = {...this.queryParam};
        if(this.selectedRowKeys && this.selectedRowKeys.length>0){
          param['selections'] = this.selectedRowKeys.join(",")
        }
        console.log("导出参数",param)
        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+'.xlsx')
          }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+'.xlsx')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link); //下载完成移除元素
            window.URL.revokeObjectURL(url); //释放掉blob对象
          }
        })
      },
      //验收
      handleCheckOrder(record){
        this.$refs.modalCheckForm.edit(record)
        this.$refs.modalCheckForm.title = '验收'
        this.$refs.modalCheckForm.disableSubmit = false
      },
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
  ::v-deep .ant-table-pagination{
    float: none;
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>