<template>
  <page-layout :title="'订单编号：'+model.orderNumber">
    <detail-list slot="headerContent" size="small" :col="2" class="detail-layout" style="padding-bottom: 32px">
      <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>
        <div class="heading">{{model.status_text}}</div>
      </a-col>
    </a-row>
    <!-- actions -->
    <template slot="action">
      <template v-if="model.status == 0">
        <template v-if="model.contractType != 2">
          <a-button @click="handleOkOrder(model)" type="primary" v-has="'order:confirm'">确认订单</a-button>
          <a-divider type="vertical" v-has="'order:close'"/>
        </template>
        <a-button @click="handleCloseOrder(model)" v-has="'order:close'">关闭订单</a-button>
      </template>
      <template v-if="model.status == 2">
        <a-button @click="handleLimitOrder(model)" type="primary" v-has="'order:limit'">中止订单</a-button>
      </template>
    </template>
    <!-- 操作 -->
    <a-card :bordered="false" :loading="loading" :tabList="tabList"
            :activeTabKey="activeTabKey"
            @tabChange="key => handleTabChange(key, 'activeTabKey')">
      <template v-if="activeTabKey === '1'">
        <detail-list title="订单信息">
          <detail-list-item term="发布人">{{model.username}}</detail-list-item>
          <detail-list-item term="接单人">{{model.hwusername}}</detail-list-item>
          <detail-list-item term="结算方式">{{model.hwRequirement.settlementMethod ==0?'一次性结算':'分期结算'}}</detail-list-item>
          <detail-list-item term="订单期数">{{model.hwRequirement.settlementMethod ==1?model.hwRequirement.stage+'期':''}}
          </detail-list-item>
          <detail-list-item term="参考单价">{{model.hwRequirement.price}}</detail-list-item>
          <detail-list-item term="参考总价">{{model.totalPrice}}</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="验收要求">
          {{model.hwRequirement.acceptanceCriteria}}
        </detail-list>
        <a-divider style="margin-bottom: 32px"/>
        <detail-list title="相关合同">
          <!--<detail-list-item term="服务合同">-->
            <!--{{model.hwRequirement.contractType == 0?'线上合同':'线下合同'}}-->
            <!--<div class="text" style="margin-top: 10px;">-->
              <!--<a @click="handleWorkDownload(model.hwRequirement.serviceContract)">下载合同</a>-->
              <!--<a @click="handleEditRequireModal(model.hwRequirement)" style="margin-left: 15px" v-has="'order:serviceEdit'">修改</a>-->
            <!--</div>-->
          <!--</detail-list-item>-->
          <!--<detail-list-item term="转包合同" v-if="model.hwRequirement.subcontractType != null">-->
            <!--{{model.hwRequirement.subcontractType == 0?'线上合同':'线下合同'}}-->
            <!--<div class="text" style="margin-top: 10px;">-->
              <!--<a @click="handleWorkDownload(model.hwRequirement.subcontract)">下载合同</a>-->
              <!--<a @click="handleEditRequireSubModal(model.hwRequirement)" style="margin-left: 15px" v-has="'order:subcontractEdit'">修改</a>-->
            <!--</div>-->
          <!--</detail-list-item>-->
          <detail-list-item term="用户合同" v-has="'order:workContract'">
            <template v-if="model.contractType === 0 ||model.contractType === 1">
              {{model.contractType === 0 ? model.workContract ? '线上合同(已上传)':'线上合同(未上传)':'线下合同'}}
              <div class="text" style="margin-top: 10px;">
                <a @click="handleWorkDownload(model.workContract)">下载合同</a>
                <a @click="handleSelectEditModal(model)" style="margin-left: 15px">修改</a>
              </div>
            </template>
            <template v-else-if="model.contractType === 2">
              电子合同{{model.electronicContractStatus !==2? electronicContractStatus_dictText?'('+electronicContractStatus_dictText+')':'' : ''}}
              <template v-if="model.electronicContractStatus === 2">
                <div class="text" style="margin-top: 10px;">
                  <a @click="handleWorkDownloadEC(model.workContract)">下载合同</a>
                  <a @click="handleSelectEditModal(model)" style="margin-left: 15px" v-has="'order:editEContractTop'">修改</a>
                </div>
              </template>
              <template v-else-if="model.electronicContractStatus === null || model.electronicContractStatus === 3 || model.electronicContractStatus === 4 || model.electronicContractStatus === 5">
                <div class="text" style="margin-top: 10px;">
                  <a @click="handleSelectEditModal(model)" v-has="'order:editEContract'">修改</a>
                </div>
              </template>
              <template v-else>

              </template>
            </template>
          </detail-list-item>
        </detail-list>
        <a-divider style="margin-bottom: 32px"/>
      </template>
      <template v-if="activeTabKey === '2'">
        <a-timeline>
            <template v-for="(item ,i) in model.hwOrderProcessDetailList">
              <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>
            </template>
        </a-timeline>
      </template>

      <hw-order-select-modal ref="modalSelectForm" @ok="modalFormOk"></hw-order-select-modal>
      <hw-order-select-require-modal ref="modalSelectRequireForm" @ok="modalFormOk"></hw-order-select-require-modal>
      <hw-order-select-require-sub-modal ref="modalSelectRequireSubForm" @ok="modalFormOk"></hw-order-select-require-sub-modal>
    </a-card>
  </page-layout>
</template>

<script>

  import HwOrderSelectModal from './HwOrderSelectModal'
  import HwOrderSelectRequireModal from './HwOrderSelectRequireModal'
  import HwOrderSelectRequireSubModal from './HwOrderSelectRequireSubModal'
  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'

  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',
    components: {
      PageLayout,
      ABadge,
      DetailList,
      DetailListItem,
      STable,
      JDate,
      HwOrderSelectModal,
      HwOrderSelectRequireModal,
      HwOrderSelectRequireSubModal
    },
    data() {
      return {
        tabList: [
          {
            key: '1',
            tab: '详情'
          },
          {
            key: '2',
            tab: '进度明细'
          }
        ],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        activeTabKey: '1',
        loading: false,
        model: {},
        electronicContractStatus_dictText:'',
        validatorRules: {
          contractType: { rules: [{ required: true, message: '请输入合同方式' }] }
        },
        detailLength: 0,
        url: {
          add: '/ordermanager/hwOrder/add',
          edit: '/ordermanager/hwOrder/edit',
          getColumns: '/ordermanager/hwOrder/detail?id=',
          downloadUrl: window._CONFIG['domianURL'] + '/hpSys/common/ossDownload'
        }
      }
    },
    created() {
      this.initAutoListConfig().then(() => {

      }).catch(msg => {
        console.log(msg)
      })
    },
    watch: {
      '$route'() {
        // 刷新参数放到这里去触发，就可以刷新相同界面了
        this.initAutoListConfig().then(() => {

        }).catch(msg => {
          console.log(msg)
        })
      }
    },
    computed: {},
    methods: {
      resetData() {
        this.model = {};
      },
      initAutoListConfig() {
        return new Promise((resolve, reject) => {
          if (!this.$route.params.code) {
            reject('列表加载需要参数CODE为空!')
          } else {
            this.resetData()
            this.loading = true
            this.code = this.$route.params.code
            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
            console.log('df===', this.model)
            if(res.result.status === 2){
              if(res.result.serviceStage){
                status =  '第'+res.result.serviceStage+'期服务中';
              }
            }
            this.model.status_text = status
            this.detailLength = res.result.hwOrderProcessDetailList.length
            this.model.totalPrice = res.result.hwRequirement.settlementMethod === 0 ? res.result.hwRequirement.price : this.accMul(res.result.hwRequirement.price, res.result.hwRequirement.stage)
          } 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)
      },
      //选择类型
      handleSelectModal(model) {
        this.$refs.modalSelectForm.edit(model)
        this.$refs.modalSelectForm.title = '选择合同类型'
        this.$refs.modalSelectForm.disableSubmit = false
      },
      //修改用户合同
      handleSelectEditModal(model) {
        this.$refs.modalSelectForm.edit(model)
        this.$refs.modalSelectForm.title = '修改用户合同'
        this.$refs.modalSelectForm.disableSubmit = false
      },
      //修改服务合同
      handleEditRequireModal(mod){
        this.$refs.modalSelectRequireForm.edit(mod)
        this.$refs.modalSelectRequireForm.title = '修改合同'
        this.$refs.modalSelectRequireForm.disableSubmit = false
      },
      //修改转包合同
      handleEditRequireSubModal(mod){
        this.$refs.modalSelectRequireSubForm.edit(mod)
        this.$refs.modalSelectRequireSubForm.title = '修改合同'
        this.$refs.modalSelectRequireSubForm.disableSubmit = false
      },
      //选择合同回调
      modalFormOk() {
        this.initAutoListConfig().then(() => {

        }).catch(msg => {
          console.log(msg)
        })
      },
      //下载合同
      handleWorkDownload(fileName) {
        if(!fileName){
          this.$message.warning("未知的文件")
          return;
        }
        if(fileName.indexOf(",")>0){
          fileName = fileName.substring(0,fileName.indexOf(","))
        }
        window.open(this.url.downloadUrl + '?fileName=' + fileName);
      },
      //下载合同(电子合同)
      handleWorkDownloadEC(fileName) {
        if(!fileName){
          this.$message.warning("未知的文件")
          return;
        }
        window.open(fileName);
      },
      accMul(num1,num2){
        var m = 0, s1 = num1.toString(), s2 = num2.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)
      }

    }
  }
</script>
<style lang="scss" scoped>
  .title {
    color: rgba(0, 0, 0, .85);
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 16px;
  }

  .detail-layout {
    margin-left: 44px;
  }

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

  .heading {
    color: rgba(0, 0, 0, .85);
    font-size: 20px;
  }

  .step-item {
    min-height: 148px !important;
  }
</style>