<template>
  <div v-if="services">
    <!-- 服务包信息 -->
    <a-card
      :bordered="false"
      style="margin-top: 24px"
      :title="`服务包信息 下单时间:(${ services.paid_at })`"
    >
      <template #extra>
        <a
          @click="refresh"
          style="margin-right:20px;margin-left:20px;"
        ><a-icon type="sync" /></a>
        <span v-if="(base.unpay > 0)">
          <span style="color:#ff4d4f;">共1条待补差价 </span>
          <a-tooltip>
            <template slot="title">发起了补差价，等待用户完成补差价操作才可以处理其他事项！</template>
            <a-icon
              type="info-circle"
              :style="{ fontSize: '16px', color: '#ff4d4f', padding: '0 0 0 10px' }"
            />
          </a-tooltip>
        </span>
        <a
          class="active"
          @click="payDiff({ id: itemId })"
          v-if="can.diff && (base.unpay == 0)"
        ><a-icon
          type="red-envelope"
          color="green"
        />补差价</a>
      </template>
      <a-descriptions>
        <a-descriptions-item label="归属工作室">{{ services.center || '-' }}</a-descriptions-item>
        <a-descriptions-item label="顾问">{{ services.parent }}</a-descriptions-item>
      </a-descriptions>
      <!-- 服务包信息 -->
      <a-table
        :rowKey="(record, index) => index"
        :bordered="true"
        size="middle"
        :columns="columns"
        :pagination="false"
        :scroll="{ x: 1500, y: 400 }"
        :data-source="services.data"
      >
        <!-- 订单编号 -->
        <span slot="order_no">{{ services.order_no }}</span>
        <!-- 服务包总金额 -->
        <span slot="amount" slot-scope="text, record">￥{{ record.amount || '0.00' }}</span>

        <!-- 机构2名称 -->
        <span slot="institution_title" slot-scope="text, record">{{ record.institution_title || '-' }}</span>

        <!-- 状态2名称 -->
        <span slot="status_two_text" slot-scope="text, record">{{ record.status_two_text || '-' }}</span>

        <!-- 退款金额 -->
        <span
          slot="refund_total"
          slot-scope="text, record"
        >
          <!-- 可编辑 -->
          <a-input
            v-if="record.editable && services.can_price"
            prefix="￥"
            v-model="editValue.refund_total"
          />
          <!-- 不编辑 -->
          <span v-else>￥{{ record.refund_total || '0.00' }}</span>
        </span>
        <!-- 欠款金额 -->
        <span
          slot="price"
          slot-scope="text, record"
        >
          <!-- 可编辑 -->
          <a-input
            v-if="record.editable && services.can_price"
            prefix="￥"
            v-model="editValue.price"
          />
          <!-- 不编辑 -->
          <span v-else>￥{{ record.price || '0.00' }}</span>
        </span>
        <!-- 匹配额度 -->
        <span
          slot="allocation"
          slot-scope="text, record"
        >
          <!-- 可编辑 -->
          <a-input
            v-if="record.editable && services.can_price"
            prefix="￥"
            v-model="editValue.allocation"
          />
          <!-- 不编辑 -->
          <span v-else>￥{{ record.allocation || '0.00' }}</span>
        </span>
        <!-- 时效 -->
        <span
          slot="prescription"
          slot-scope="text, record"
        > {{ record.prescription>0 ? record.prescription + '天' : '-' }}</span>

        <!-- 申请时间 -->
        <div
          slot="audit_at"
          slot-scope="text, record"
        >

          <!-- 可编辑 -->
          <a-date-picker
            v-if="record.editable && services.can_audit_settle_time"
            :default-value="record.audit_at != '' ? moment(record.audit_at, dateFormat) : ''"
            placeholder="选择申请时间"
            @change="dateChange('audit_at', $event)"
          />
          <!-- 不编辑 -->
          <span v-else><span>{{ record.audit_at || '-' }}</span></span>
        </div>

        <!-- 结案时间 -->
        <div
          slot="settle_at"
          slot-scope="text, record"
        >
          <!-- 可编辑 -->
          <a-date-picker
            v-if="record.editable && services.can_audit_settle_time"
            :default-value="record.settle_at !='' ? moment(record.settle_at, dateFormat) : ''"
            placeholder="选择结案时间"
            @change="dateChange('settle_at', $event)"
          />
          <!-- 不编辑 -->
          <span v-else ><span>{{ record.settle_at || '-' }}</span></span>
        </div>
        <!-- 机构名称2 -->
        <!-- <span
          slot="institution_name"
          slot-scope="text, record"
        >{{ record.institution_name || '-' }}</span> -->

        <!-- 操作按钮 -->
        <div
          slot="actions"
          slot-scope="text, record, index"
        >
          <a
            v-if="!record.editable"
            @click="() => editService(record.item_id, index)"
          >编辑</a>
          <template v-else>
            <a @click="() => cancelService(record.item_id, index)">取消</a>
            <a-divider type="vertical" />
            <a @click="() => editServiceInfo(record.item_id, index)">保存</a>
          </template>
        </div>
      </a-table>

      <div style="display:flex;margin-top: 30px;">
        补差价次数:<span style="margin-right:30px;color:#1890ff;">{{ base.count }}次</span>
        待补差价:<span style="margin-right:30px;color:#1890ff;">￥{{ base.unpay }}</span>
        已补差价:<span style="margin-right:30px;color:#1890ff;">￥{{ base.paid }}</span>
        服务包金额:<span style="margin-right:30px;color:#1890ff;">￥{{ base.total }}</span>
      </div>
      <div>
        <a-timeline :reverse="true">
          <a-timeline-item
            v-for="item in diffsList"
            :key="item.diff_id"
          >
            <a-card
              :bordered="true"
              style="margin-top: 24px"
              :title="item.status"
            >
              <template #extra>
                <a-popconfirm
                  v-if="item.is_delete"
                  title="是否确认撤回该条补差价?"
                  ok-text="确认"
                  cancel-text="取消"
                  @confirm="diffBack(item.diff_id)"
                >
                  <a> <a-icon
                    type="delete"
                    :style="{ fontSize: '14px', color: '#1890ff', padding: '6px 6px 6px 0' }"
                  />撤回补差价</a>
                </a-popconfirm>
              </template>
              <a-descriptions>
                <a-descriptions-item label="创建时间"> {{ item.created_at }}</a-descriptions-item>
                <a-descriptions-item label="操作人 ">{{ item.operate.name }}({{ item.operate.type }})</a-descriptions-item>
                <a-descriptions-item label="操作类型 ">发起<a>{{ item.ins != '' ? '机构' : '服务包' }}</a>补差价</a-descriptions-item>
                <a-descriptions-item
                  label="操作机构"
                  v-if="item.ins != ''"
                >{{ item.ins }}</a-descriptions-item>
                <a-descriptions-item label="补差金额"> ￥{{ item.price }}</a-descriptions-item>
                <a-descriptions-item label="备注原因"> {{ item.remark }}</a-descriptions-item>
              </a-descriptions>
            </a-card>
          </a-timeline-item>
        </a-timeline>
      </div>

      <!-- 备注 -->
      <div class="or-remark">
        <H4>备注：</H4>
        <div
          style="flex:1;"
          v-if="canRemark"
        >
          {{ remark }} <a-icon
            @click="remarkNew = remark, canRemark = false"
            type="edit"
            :style="{ fontSize: '15px', color: '#1890ff',padding:'0 14px' }"
          />
        </div>
        <a-textarea
          v-else
          class="or-remark-inpu"
          v-model="remarkNew"
          placeholder="备注：对订单服务包进行的备注说明"
          :auto-size="{ minRows: 5, maxRows: 7 }"
        >
        </a-textarea>
      </div>
      <a-button
        v-if="!canRemark"
        style="margin-left:50px;margin-top:10px;"
        type="primary"
        @click="sureRemark"
      >确认修改 </a-button>
    </a-card>

  </div>
</template>
<script>
import ItemPopover from './modules/ItemPopover.vue'
import { remark, editServiceInfo } from '@/api/organization'
import moment from 'moment'
import PayDifference from '@/components/OrderDetailInfo/modules/PayDifference.vue'
import { getAllBanks, diffPayList, diffBack } from '@/api/order'
export default {
  components: {
    ItemPopover
  },
  name: 'OrganizationServiceInfo',
  props: {
    itemId: {
      type: String,
      default: ''
    },
    orderId: {
      type: String,
      default: ''
    },
    services: {
      type: Object,
      default: () => {
        return []
      }
    },
    can: {
      type: Object,
      default: () => {
        return {}
      }
    },
    remark: {
      type: String,
      default: ''
    }

  },
  data () {
    return {
      columns: [
        {
          title: '订单编号',
          scopedSlots: { customRender: 'order_no' },
          customRender: (value, row, index) => {
            const obj = {
              children: `${this.services.order_no}`,
              attrs: {}
            }
            if (index === 0) {
              obj.attrs.rowSpan = this.services.data.length // 合并数量 纵向合并
              // obj.attrs.colSpan = 3 // 横向合并
            }
            if (index >= 1) {
              obj.attrs.rowSpan = 0 // 合并数量 纵向合并
              // obj.attrs.colSpan = 0 // 横向合并
            }
            return obj
          },
          width: 150,
          align: 'center'
        },
        {
          title: '机构名称',
          dataIndex: 'title',
          width: 140,
          align: 'center'
        },
        {
          title: '机构名称2',
          scopedSlots: { customRender: 'institution_title' },
          width: 140,
          align: 'center'
        },
        {
          title: '机构状态',
          width: 110,
          dataIndex: 'status_text',
          align: 'center'
        },
        {
          title: '机构状态2',
          width: 110,
          scopedSlots: { customRender: 'status_two_text' },
          align: 'center'
        },
        {
          title: '订单金额',
          dataIndex: 'total',
          align: 'center',
          width: 220,
          customRender: (value, row, index) => {
            const obj = {
              children: this.$createElement(
                'div',
                [
                  this.$createElement('div'),
                  '服务包总金额:￥' + this.services.order_total,
                  this.$createElement('div'),
                  '服务包现金:￥' + this.services.total,
                  this.$createElement('div'),
                  '服务包火力值:￥' + this.services.fire,
                  this.$createElement('div'),
                  '补差价总额:￥' + this.services.diff_total,
                  this.$createElement('div'),
                  '补差价现金:￥' + this.services.diff_cash,
                  this.$createElement('div'),
                  '补差价火力值:￥' + this.services.diff_fire,
                  this.$createElement('div'),
                  '退款总额:￥' + this.services.refund_fire
                ]
              ),
              attrs: {}
            }
            if (index === 0) {
              obj.attrs.rowSpan = this.services.data.length // 合并数量 纵向合并
              // obj.attrs.colSpan = 3 // 横向合并
            }
            if (index >= 1) {
              obj.attrs.rowSpan = 0 // 合并数量 纵向合并
              // obj.attrs.colSpan = 0 // 横向合并
            }
            return obj
          }
        },
        {
          title: '服务包金额',
          width: 110,
          scopedSlots: { customRender: 'amount' },
          align: 'center'
        },
        {
          title: '退款金额',
          width: 110,
          scopedSlots: { customRender: 'refund_total' },
          align: 'center'
        }, {
          title: '欠款金额',
          width: 110,
          scopedSlots: { customRender: 'price' },
          align: 'center'
        }, {
          title: '匹配额度',
          width: 110,
          scopedSlots: { customRender: 'allocation' },
          align: 'center'
        }, {
          title: '申请时间',
          scopedSlots: { customRender: 'audit_at' },
          width: 160,
          align: 'center'
        }, {
          title: '结案时间',
          scopedSlots: { customRender: 'settle_at' },
          width: 160,
          align: 'center'
        }, {
          title: '处理时效',
          scopedSlots: { customRender: 'prescription' },
          width: 120,
          align: 'center'
        }, {
          title: '操作',
          scopedSlots: { customRender: 'actions' },
          align: 'center',
          width: 120
        }
      ],
      editValue: { // 编辑时的基本信息
        audit_at: '', // 申请时间
        settle_at: '', // 结案时间
        price: '', // 欠款金额
        refund_total: '', // 退款金额
        allocation: '' // 匹配金额
      },
      remarkNew: '',
      canRemark: true,
      editingKey: '', // 服务包修改申请时间，结案时间 的id
      dateFormat: 'YYYY/MM/DD',
      banks: [], // 活的所有机构列表
      diffsList: [], // 补差价列表
      base: '' // 补差价基本信息
    }
  },
  created () {
    this.getPayDiff()
  },
  activated () {
    this.getPayDiff()
  },
  methods: {
    moment,
    // 点击编辑服务包
    editService (id) {
      const newData = [...this.services.data]
      const target = newData.find(item => id === item.item_id)
      // 有 key 意味着第二次以上的选择编辑要进行判断，判断是否有，还是上次点击遗留下来的数据，然后再清空和赋值
      if (this.editingKey !== id && this.editingKey !== '') {
        const targetOld = newData.find(item => this.editingKey === item.item_id)
        if (targetOld) {
          this.editValue = {
            audit_at: '', // 申请时间
            settle_at: '', // 结案时间
            price: '', // 欠款金额
            allocation: '', // 匹配金额
            refund_total: '' // 退款金额
          }
          targetOld.editable = false
        }
        this.editingKey = id
      } else {
        // 第一次选择编辑直接赋值
        this.editingKey = id
      }
      if (target) {
        target.editable = true
        this.editValue = {
          audit_at: target.audit_at, // 申请时间
          settle_at: target.settle_at, // 结案时间
          price: target.price, // 欠款金额
          allocation: target.allocation, // 匹配金额
          refund_total: target.refund_total // 退款金额
        }
        this.services.data = newData
      }
    },
    // 取消编辑服务包
    cancelService (id) {
      const newData = [...this.services.data]
      const target = newData.find(item => id === item.item_id)
      this.editingKey = ''
      if (target) {
        target.editable = false
        this.editValue = {
          audit_at: '', // 申请时间
          settle_at: '', // 结案时间
          price: '', // 欠款金额
          allocation: '', // 匹配金额
          refund_total: '' // 退款金额
        }
        this.services.data = newData
      }
      // 需要刷新一下接口，
    },
    /**
     * 保存服务包
     * @param {*} id 机构 id
     */
    editServiceInfo (id) {
      editServiceInfo(this.editingKey, this.editValue).then(res => {
        this.eventBus.$emit('updateOrderInfo', { data: true })
        this.cancelService(this.editingKey)
      }).catch(err => {
        console.log(err)
      })
    },

    /**
     * 确认选择了年月日时分秒
     * @param {*} type  当前修改类型
     * @param {*} value 日期返回值
     */
    dateChange (type, value) {
      this.editValue[`${type}`] = moment(value).format('YYYY-MM-DD')
    },
    // 新添加备注信息
    sureRemark () {
      remark(this.itemId, {
        remark: this.remarkNew
      }).then(res => {
        this.eventBus.$emit('updateOrderInfo', { data: true })
        this.canRemark = true
      }).catch(err => {
        console.log(err)
      })
    },
    // 补差价处理弹窗
    payDiff (item) {
      // 获得所有机构信息
      getAllBanks(this.orderId).then(res => {
        item.banks = res
        item.id = this.orderId
        this.$dialog(
          PayDifference,
          {
            item,
            on: {
              ok: () => {
                this.refresh()
              }
            }
          },
          {
            title: '给服务包/机构补差价',
            width: 500,
            maskClosable: true,
            closable: true,
            okText: '确认补差价',
            cancelText: '取消'
          }
        )
      }).catch(err => {
        console.log(err)
      })
    },
    refresh () {
      this.eventBus.$emit('updateOrderInfo', { data: true })
      this.getPayDiff()
    },
    // 获得补差价列表
    getPayDiff () {
      diffPayList(this.orderId).then(res => {
        this.diffsList = res.lists
        this.base = res.base
      }).catch(err => {
        this.$error(err.message)
      })
    },
    // 撤回补差价
    diffBack (id) {
      diffBack(this.orderId, id).then(res => {
        this.$notification.success({
          message: '成功',
          description: '操作成功！'
        })
        this.eventBus.$emit('updateOrderInfo', { data: true })
        this.getPayDiff()
      }).catch(err => {
        this.$error(err.message)
      })
    }
  }
}
</script>
<style lang="less" scoped>
.row {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
}
.column {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
}
.ai_start {
  align-items: flex-start;
}
.jc_start {
  justify-content: flex-start;
}
.jc_sb {
  justify-content: space-between;
}
.js_start {
  justify-content: start;
}
.a-des-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  box-sizing: border-box;
  .pl50 {
    margin-left: 50px;
  }
  .inputT {
    flex: 1;
    margin-left: 50px;
  }
}
.or-remark {
  display: flex;
  flex-direction: row;
  box-sizing: border-box;
  margin-top: 30px;
  .or-remark-input {
    flex: 1;
    margin-left: 20px;
  }
  h4 {
    width: 50px;
  }
}
</style>
