<template>
  <a-modal
    :title='title'
    :width='modelStyle.width'
    :bodyStyle='bodyStyle'
    :visible='visible'
    :confirmLoading='confirmLoading'
    :maskClosable='false'
    @ok='handleOk'
    @cancel='handleCancel'
    cancelText='关闭'>
    <page-layout :noBreadcrumb='true' style='width: 100%'>
      <detail-list slot='headerContent' size='small' class='order-number' style='padding-top: 40px'>
        <detail-list-item term='订单编号'>{{ model.orderNumber }}</detail-list-item>
      </detail-list>
      <detail-list slot='headerContent' size='small' class='detail-layout' style='padding-bottom: 30px'>
        <detail-list-item term='需求单号'>{{ model.requireCode }}</detail-list-item>
      </detail-list>
      <a-row slot='extra' class='status-list'>
        <a-col :xs='24' :sm='24'>
          <!--          <div class='text'>状态</div>-->
          <a-icon type='question-circle' style='color: rgba(255, 197, 61, 1)' v-if='model.status == "0"' />
          <a-icon type='info-circle' style='color: rgba(0, 0, 0, 0.25)' v-if='model.status == "1"' />
          <a-icon type='clock-circle' style='color: rgba(105, 192, 255, 1)' v-if='model.status == "2"' />
          <a-icon type='minus-circle' style='color: rgb(154,21,37)' v-if='model.status == "3"' />
          <a-icon type='check-circle' style='color: rgba(82, 196, 26, 1)' v-if='model.status == "4"' />
          <div class='heading'>{{ model.status_text }}</div>
        </a-col>
      </a-row>
      <!-- actions -->
      <!-- 操作 -->
      <a-spin :spinning='confirmLoading'>
        <a-card :bordered='false' :loading='loading' :tabList='tabList' class='order-detail-info'
                :activeTabKey='activeTabKey'
                @tabChange="key => handleTabChange(key, 'activeTabKey')">
          <template v-if="activeTabKey === '1'">
            <detail-list title='订单信息'>
              <detail-list-item term='发布人'>{{ model.companyName }}</detail-list-item>
              <detail-list-item term='接单人'>{{ model.userName }}</detail-list-item>
              <detail-list-item term='手机号'>{{ model.userPhone }}</detail-list-item>
              <detail-list-item term='参考单价'>{{ model.hwRequirement.price }}</detail-list-item>
              <detail-list-item term='创建时间'>{{ model.createTime }}</detail-list-item>
            </detail-list>
            <!--        <a-divider style="margin-bottom: 32px"/>-->
            <detail-list title='订单描述'>
              {{ model.hwRequirement.description }}
            </detail-list>
            <!--        <a-divider style="margin-bottom: 32px"/>-->
            <detail-list title='验收要求' style="margin-bottom: 32px">
              {{ model.hwRequirement.acceptanceCriteria }}
            </detail-list>
            <!--        <a-divider style="margin-bottom: 32px"/>-->
            <detail-list title='相关合同' :col='1' v-has="'order:contract'">
              <detail-list-item term='甲方签章' v-if='model.workContractType === 1'>
                {{ model.partASign }}
              </detail-list-item>

              <a-table
                ref='table'
                size='middle'
                bordered
                rowKey='id'
                :columns='columns'
                :pagination='pagination'
                :dataSource='dataSource'
                :loading='loading'
                @change='handleTableChange'>

                  <span slot='endDate' slot-scope='text, record'>
                    <template v-if='record.isAutoRenew === 0 && text'>
                      <template v-if='record.contractStatus == 1'>
                        <span style='color: #FF7312'>{{ text.length > 10 ? text.substring(0, 10) : text }}(即将到期)</span>
                      </template>
                      <template v-else-if='record.contractStatus == 2'>
                        <span style='color: #F01B1B'>{{ text.length > 10 ? text.substring(0, 10) : text }}(已到期)</span>
                      </template>
                      <template v-else>
                        {{ text.length > 10 ? text.substring(0, 10) : text }}
                      </template>
                    </template>
                    <template v-else>
                       --
                    </template>
                  </span>

                  <span slot='isPayment' slot-scope='text, record'>
                    <template v-if='record.isPayment'>
                      已走款：{{ record.minPaymentTime.length > 10 ? record.minPaymentTime.substring(0, 10) : record.minPaymentTime
                      }}~{{ record.maxPaymentTime.length > 10 ? record.maxPaymentTime.substring(0, 10) : record.maxPaymentTime
                      }}
                    </template>
                    <template v-else>
                      未走款
                    </template>
                  </span>

                  <span slot='workContract' slot-scope='text, record'>
                    <a @click='uploadWorkContract(record)'>{{ record.workContract ? '已上传' : '未上传' }}</a>
                  </span>
              </a-table>

            </detail-list>
            <a-divider style='margin-bottom: 32px' v-has="'order:contract'" />
          </template>
          <template v-if="activeTabKey === '2'">
            <a-steps direction='vertical' :current='model.hwOrderProcessDetailList.length'>
              <template v-for='(item ,index) in model.hwOrderProcessDetailList'>
                <a-step :title='item.statusText' :description='item.generateTime'>
                  <!--                <a-timeline-item>-->
                  <!--                  <a-icon slot='dot' type='clock-circle-o' style='font-size: 16px;' />-->
                  <!--                  <p style='margin-bottom: 0px;font-size: 14px'>{{ item.generateTime }}</p>-->
                  <!--                  <p style='font-size: 16px'>{{ item.statusText }}</p>-->
                  <!--                </a-timeline-item>-->
                </a-step>
              </template>

            </a-steps>
          </template>

          <HwOrderSubcontractorContract ref='modalSelectForm' @ok='modalFormOk'></HwOrderSubcontractorContract>
        </a-card>
      </a-spin>
    </page-layout>
    <template #footer>
      <a-button key='back' @click='handleCancel'>关闭</a-button>
      <!--      <a-button key="submit" type="primary" :loading="loading" @click="handleOk">Submit</a-button>-->
    </template>
  </a-modal>
</template>

<script>

import PageLayout from '@/components/page/PageLayout'
import STable from '@/components/table/'
import DetailList from '@/components/tools/DetailList'
import ABadge from 'ant-design-vue/es/badge/Badge'
import { httpAction, getAction, putAction, downFile } from '@/api/manage'
import pick from 'lodash.pick'
import JDate from '@/components/jeecg/JDate'
import { initDictOptions } from '@/components/dict/JDictSelectUtil'
import { axios } from '@/utils/request'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import HwOrderSubcontractorContract from './HwOrderSubcontractorContract'

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 DetailListItem = DetailList.Item

export default {
  name: 'HwOrderModal',
  mixins: [JeecgListMixin],
  components: {
    PageLayout,
    ABadge,
    DetailList,
    DetailListItem,
    STable,
    JDate,
    HwOrderSubcontractorContract
  },
  data() {
    return {
      tabList: [
        {
          key: '1',
          tab: '详情'
        },
        {
          key: '2',
          tab: '进度明细'
        }
      ],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      // 表头
      columns: [
        {
          title: '服务商',
          align: 'left',
          width: 300,
          dataIndex: 'name'
        },
        {
          title: '合同开始时间',
          align: 'left',
          dataIndex: 'startDate',
          customRender: function(text) {
            return text ? text.substring(0, 10) : '--'
          }
        },
        {
          title: '合同结束时间',
          align: 'left',
          dataIndex: 'endDate',
          scopedSlots: { customRender: 'endDate' }
        },
        {
          title: '走款情况',
          align: 'left',
          dataIndex: 'isPayment',
          scopedSlots: { customRender: 'isPayment' }
        },
        {
          title: '用户合同',
          align: 'left',
          width: 200,
          dataIndex: 'workContract',
          scopedSlots: { customRender: 'workContract' }
        }
      ],
      activeTabKey: '1',
      loading: false,
      model: {
        hwRequirement: {}
      },
      electronicContractStatus_dictText: '',
      validatorRules: {},
      detailLength: 0,
      pagination: false,
      title: '详情',
      modelStyle: {
        width: '80%',
        style: { top: '20px' },
        fullScreen: false
      },
      visible: false,
      bodyStyle: {
        padding: '0',
        height: (window.innerHeight * 0.66) + 'px',
        'overflow-y': 'auto'
      },
      confirmLoading: false,
      code: 0,
      url: {
        add: '/ordermanager/hwOrder/add',
        edit: '/ordermanager/hwOrder/edit',
        getColumns: '/ordermanager/hwOrder/detail?id=',
        downloadUrl: window._CONFIG['domianURL'] + '/hpSys/common/ossDownload',
        list: '/ordermanager/hwOrder/subcontractList'
      }
    }
  },
  computed: {},
  methods: {
    resetData() {
      this.model = {}
    },
    loadSubData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = {}
      params.orderCode = this.model.orderNumber
      this.loading = true
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    initAutoListConfig() {
      return new Promise((resolve, reject) => {
        if (!this.code) {
          reject('列表加载需要参数CODE为空!')
        } else {
          this.resetData()
          this.loading = true
          console.log('cd', this.code)
          getAction(`${this.url.getColumns}${this.code}`)
            .then(res => {
              if (res.success) {
                this.configInfohandler(res)
                resolve()
              } else {
                reject('失败')
              }
              this.loading = false
            })
            .catch(err => {
              reject(err)
            })
        }
      })
    },
    configInfohandler(res) {
      //解析字典
      initDictOptions('order_status').then((resdict) => {
        if (resdict.success) {
          var dictOptions = resdict.result
          var text = String(res.result.status)
          let status = ''
          dictOptions.forEach(function(option) {
            if (text === option.value) {
              status = option.text
            }
          })
          this.model = res.result
          this.loadSubData(1)
          console.log('df===', this.model)
          this.model.status_text = status
          this.detailLength = res.result.hwOrderProcessDetailList.length
          this.model.totalPrice = res.result.hwRequirement.price
        } else {

        }
      })
      //解析字典
      initDictOptions('electronic_contract_status').then((resdict) => {
        if (resdict.success) {
          var dictOptions = resdict.result
          var text = String(res.result.electronicContractStatus)
          let status = ''
          dictOptions.forEach(function(option) {
            if (text === option.value) {
              status = option.text
            }
          })
          this.electronicContractStatus_dictText = status
        } else {

        }
      })
    },
    //确认订单
    handleOkOrder(record) {
      let that = this
      const modal = that.$confirm({
        title: '确认订单',
        closable: true,
        keyboard: false,
        maskClosable: true,
        content: '是否确认订单准确无误？',
        okText: '确认订单',
        cancelText: '取消',
        onOk: function() {
          confirmOrder({ id: record.id }).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.initAutoListConfig().then(() => {

              }).catch(msg => {
                console.log(msg)
              })
            } else {
              that.$error({
                title: '确认失败',
                content: res.message,
                okText: '确定'
              })
            }
          })
        },
        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.initAutoListConfig().then(() => {

              }).catch(msg => {
                console.log(msg)
              })
            } 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.initAutoListConfig().then(() => {

              }).catch(msg => {
                console.log(msg)
              })
            } else {
              that.$message.error(res.message)
            }
          })
        },
        onCancel(e) {
          modal.destroy()
        }
      })
    },
    handleTabChange(key, type) {
      this[type] = key
      this.loading = true
      setTimeout(() => {
        this.loading = false
      }, 200)
    },
    //选择合同回调
    modalFormOk() {
      this.initAutoListConfig().then(() => {

      }).catch(msg => {
        console.log(msg)
      })
    },
    //上传用户合同
    uploadWorkContract(record) {
      let recordNew = {}
      recordNew.orderCode = this.model.orderNumber
      recordNew.subcontractorId = record.id
      recordNew.isPayment = record.isPayment
      recordNew.minPaymentTime = record.minPaymentTime
      recordNew.maxPaymentTime = record.maxPaymentTime
      this.$refs.modalSelectForm.edit(recordNew)
      this.$refs.modalSelectForm.title = '用户合同--' + record.name
      this.$refs.modalSelectForm.disableSubmit = false
    },
    handleOk() {
      this.$emit('ok')
      this.close()
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('ok')
      this.visible = false
    }
  }
}
</script>
<style lang='scss' scoped>
@import '~@assets/less/common.less';

.title {
  color: rgba(0, 0, 0, .85);
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
}

::v-deep .detail-layout {
  //margin-left: 44px;
  .term {
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #000000;
  }

  .content {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: rgba(0, 0, 0, 0.65);
  }
}

.text {
  color: rgba(0, 0, 0, .45);
}

.order-number{
  font-size: 24px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 10px;
}

.status-list div {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 60px;
}

div.heading {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #000000;
  margin-top: 13px;
}

.step-item {
  min-height: 148px !important;
}

/deep/ .payFail {
  color: #D9001B;
}

::v-deep .detail-layout div {
  width: auto;
}

::v-deep .order-detail-info {
  .ant-card-body {
    .detail-list {
      .title {
        font-size: 20px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        color: rgba(0, 0, 0, 0.85);
        margin-top: 40px;
        margin-bottom: 20px;
      }

      .ant-row {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(0, 0, 0, 0.65);
      }
    }
  }
}
</style>