<template>
  <div class="detailPage">
    <div class="topButton">
      <a-button type="primary" @click="goBack">
        {{ t('common.back') }}
      </a-button>
    </div>
    <div class="content">
      <div class="content_left">
        <div class="content_left_info">
          <Descriptions title="客户信息" :column="3" v-if="detailData.customer">
            <DescriptionsItem label="客户名称">
              {{ detailData.customer.companyName }}</DescriptionsItem
            >
            <DescriptionsItem label="联系人">
              {{ detailData.customer.customerName }}
            </DescriptionsItem>
            <DescriptionsItem label="联系电话"> {{ detailData.customer.phone }} </DescriptionsItem>
          </Descriptions>
          <Descriptions title="产品及故障信息" :column="3">
            <DescriptionsItem label="产品名称" v-if="detailData.repairerVo">
              {{ t(`routes.device.type.${detailData.repairerVo.cameraType || 1}`) }}
            </DescriptionsItem>
            <DescriptionsItem label="产品SN码" v-if="detailData.repairerVo">
              {{ detailData.repairerVo.cameraSnCode }}
            </DescriptionsItem>
            <DescriptionsItem label="保修届满日期">
              {{ detailData.repairerVo.warrantyDate }}
            </DescriptionsItem>
            <DescriptionsItem label="报修日期">
              {{ detailData.repairerVo?.createTime }}
            </DescriptionsItem>
            <DescriptionsItem class="ellipsis" label="送修方式" v-if="detailData.customerAddress">
              {{
                detailData.customerAddress.sendType == 0
                  ? '前台送修'
                  : `快递寄送:${detailData.customerAddress?.sendTrackingNum || '暂无单号'}`
              }}
            </DescriptionsItem>
            <DescriptionsItem label="保修类型">
              {{
                detailData.repairerVo.warrantyType == 0
                  ? '保修期内'
                  : detailData.repairerVo.warrantyType == 1
                  ? '保内转保外'
                  : '保外维修'
              }}
            </DescriptionsItem>
            <DescriptionsItem label="维修单号">
              {{ repairId }}
            </DescriptionsItem>
            <DescriptionsItem label="上次维修单号" :span="2">
              {{ detailData.lastRepairId }}
            </DescriptionsItem>
            <DescriptionsItem label="故障描述" :span="3">
              <div>
                <p class="htmlText" :title="detailData.repairerVo.faultMsg">{{ detailData.repairerVo.faultMsg }}</p>
                <PreviewGroup>
                  <Image
                    :width="80"
                    :height="80"
                    v-for="item in detailData.repairerVo.faultImg"
                    :key="item"
                    :src="item"
                  ></Image>
                </PreviewGroup>
              </div>
            </DescriptionsItem>
            <DescriptionsItem label="机器外观">
              <div>
                <p class="htmlText" :title="detailData.orderReceivingVo?.orderFaultMsg">{{ detailData.orderReceivingVo?.orderFaultMsg }}</p>
                <PreviewGroup>
                  <Image
                    :width="80"
                    :height="80"
                    v-for="item in detailData.orderReceivingVo?.orderFaultImg"
                    :key="item"
                    :src="item"
                  ></Image>
                </PreviewGroup>
              </div>
            </DescriptionsItem>
            <DescriptionsItem label="售后工程师">
              {{ detailData.orderReceivingVo?.sysUserName }}
            </DescriptionsItem>
            <DescriptionsItem label="接单日期">
              {{ detailData.orderReceivingVo?.createTime }}
            </DescriptionsItem>
          </Descriptions>
          <!-- <Descriptions title="" :column="3">
            <DescriptionsItem label="备注内容">
              {{ detailData.repairerVo?.remark }}
            </DescriptionsItem>
          </Descriptions> -->
          <Descriptions v-for="(Voitem, index) in detailData.repairRegisterVo" :key="Voitem.createTime" :column="3">
                <DescriptionsItem :label="index=='0'?'检测结果':'维修登记'">
                <div>
                  <p class="htmlText" :title="Voitem.checkResult">{{ Voitem.checkResult }}</p>
                  <PreviewGroup>
                    <Image
                      :width="80"
                      :height="80"
                      v-for="item in Voitem.checkImg"
                      :key="item"
                      :src="item"
                    ></Image>
                  </PreviewGroup>
                </div>
              </DescriptionsItem>
              <DescriptionsItem :label="index=='0'?'检测日期':'登记日期'">
                {{ Voitem?.createTime }}
              </DescriptionsItem>
              <DescriptionsItem label="所需备件">
                {{ Voitem?.partNamesStr }}
              </DescriptionsItem>
          </Descriptions>
          <Descriptions title="维修清单" :column="3" layout="vertical">
            <DescriptionsItem label="备件信息" :span="3">
              <BasicTable @register="registerTable"></BasicTable>
            </DescriptionsItem>
          </Descriptions>
          <Descriptions :column="3">
            <DescriptionsItem label="维修工程师">
              {{ detailData.repairRegisterVo?.sysUserName }}</DescriptionsItem
            >
            <DescriptionsItem label="维修完成日期">
              {{ detailData.repairRegisterVo?.overTime }}
            </DescriptionsItem>
            <DescriptionsItem label="维修记录">
              {{ detailData.repairRegisterVo?.remark }}
            </DescriptionsItem>
            <DescriptionsItem label="测试工程师">
              {{ detailData.repairTestVo?.sysUserName }}
            </DescriptionsItem>
            <DescriptionsItem label="测试通过时间" :span="2">
              {{ detailData.repairTestVo?.passTime }}
            </DescriptionsItem>
            <DescriptionsItem label="支付方式" :span="3">
              <div v-if="detailData.repairPay">
                <p>{{
                  detailData.repairPay.payType == 1
                    ? '微信'
                    : detailData.repairPay.payType == 2
                    ? '支付宝'
                    : '银行'
                }}</p>
                <PreviewGroup>
                  <Image
                    :width="80"
                    :height="80"
                    v-for="item in detailData.repairPay.payImg"
                    :key="item"
                    :src="item"
                  ></Image>
                </PreviewGroup>
              </div>
            </DescriptionsItem>
            <DescriptionsItem label="取回方式" v-if="detailData.customerAddress">
              {{
                detailData.customerAddress.getType == 0
                  ? '前台取回'
                  : `快递寄回 ${detailData.customerAddress?.getTrackingNum || '暂无单号'}`
              }}</DescriptionsItem
            >
            <DescriptionsItem label="收件信息" :span="2" v-if="detailData.customerAddress">
              {{ detailData.customerAddress.getAddrName }}
              {{ detailData.customerAddress.getAddress }}
            </DescriptionsItem>
          </Descriptions>
          <Descriptions title="单据下载" :column="3" v-if="detailData.repairerVo.status > 30">
            <DescriptionsItem label="报价单" :span="3" v-if="detailData.repairerVo.status > 30"> 
                <div class="link" @click="dowmFile(0)"> {{repairId}}报价单.xlsx</div>  
            </DescriptionsItem>
            <DescriptionsItem label="维修工单" :span="3" v-if="detailData.repairerVo.status > 70"> 
              <div class="link" @click="dowmFile(1)"> {{repairId}}维修工单.xlsx</div>  
            </DescriptionsItem>
          </Descriptions>
          <Descriptions title="客户评价" :column="3" v-if="detailData.RepairComment">
            <DescriptionsItem label="评价内容">
              {{ detailData.RepairComment.comment }}
            </DescriptionsItem>
            <DescriptionsItem label="评分">
              {{ detailData.RepairComment.starRank }}
            </DescriptionsItem>
          </Descriptions>
          <Descriptions title="备注" :column="3">
            <DescriptionsItem label="备注内容">
              {{ detailData.repairerVo?.remark }}
            </DescriptionsItem>
          </Descriptions>
        </div>
      </div>
      <div class="content_right">
        <Timeline>
          <a-timeline>
          <timeline-item
            v-for="(item, indexs) in stepList"
            :color="indexs == 0 ? 'red' : 'green'"
            :key="indexs"
          >
            <div class="timeItem">
              <div class="name">
                <span>{{ item.remark }}</span>
                <a-button
                  style="margin-left: 50px"
                  @click="handleBut(butItem)"
                  v-for="butItem in butList"
                  :key="butItem"
                  v-if="indexs == 0"
                >
                  {{ butItem }}
                </a-button>
              </div>
              <div class="status"
                >{{ item.sysUserName }}完成{{ item.remark }} <span>{{ item.createTime }}</span></div
              >
              <div class="itemText" v-if="item.customerAddress">{{
                item.customerAddress.getType == 0
                  ? '前台取回'
                  : `快递寄回  ${item.customerAddress.getTrackingNum}`
              }}</div>
              <div class="itemText" v-if="item.customerAddress">{{
                item.customerAddress.sendType == 0
                  ? '前台送修'
                  : `快递寄送  ${item.customerAddress.sendTrackingNum}`
              }}</div>
              <div class="itemText" v-if="item.repairRegisterVo"
                >检测结论： {{ item.repairRegisterVo.checkResult }}</div
              >
              <div class="itemText" v-if="item.repairRegisterVo"
                >所需备件： {{ item.repairRegisterVo.partNamesStr }}</div
              >
              <div class="itemText" v-if="item.orderReceivingVo"
                >机器外观： {{ item.orderReceivingVo.orderFaultMsg }}</div
              >
              <div class="iamgeList">
                <PreviewGroup>
                  <Image style="overflow:hidden"
                    :width="80"
                    :height="80"
                    v-for="itemSrc in item.imagesInfo"
                    :key="itemSrc"
                    :src="itemSrc"
                  ></Image>
                </PreviewGroup>
              </div>
            </div>
          </timeline-item>
        </a-timeline>
        </Timeline>
      </div>
    </div>
    <div class="bottom_but">
      <a-button type="primary" v-for="item in butList" :key="item" @click="handleBut(item)">
        {{ item }}
      </a-button>
      <a-button type="primary" @click="goBack">
        {{ t('common.back') }}
      </a-button>
    </div>
    <!-- <recoveryModal @update="reload" @register="registerRecovery" /> -->
    <remarksModal @update="reload" @register="registerRemarks" />
    <takingOrdersModel @update="reload" @register="registerTakingOrders" />
    <quoteModel @update="reload" @register="registerQuote" />
    <deliveryModal @update="reload" @register="registerDelivery" />
    <payLogModal @update="reload" @register="registerPayLog" />
    <partsListModal @update="reload" @register="registerParts" />
    <checkModel @update="reload" @register="registerCheck" />
    <addAccessoryModel @update="reload" @register="registerAdd" />
    <outModal @update="reload" @register="registerOut" />
    <reviewModal @update="reload" @register="registerReview" />
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, onMounted, reactive, h } from 'vue';
import { useI18n } from '/@/hooks/web/useI18n';
import { useRouter } from 'vue-router';
import { useMessage } from '/@/hooks/web/useMessage';
import { detail, process, detailDownExport } from '/@/api/spares';
import { detailResult } from '/@/api/spares/model';
import { useModal } from '/@/components/Modal';
// import recoveryModal from './recoveryModal.vue';//录单
import quoteModel from './quoteModel.vue';
import deliveryModal from './deliveryModal.vue';
import payLogModal from './payLogModal.vue';
import takingOrdersModel from './takingOrdersModel.vue';
import remarksModal from '../spares/remarksModal.vue';
import checkModel from './checkModel.vue';
import partsListModal from './partsListModal.vue';
import outModal from './outModal.vue';
import reviewModal from './reviewModal.vue';
import { cloneDeep } from 'lodash-es';
import addAccessoryModel from './addAccessoryModel.vue';
import { usePermissionStore } from '/@/store/modules/permission';
import { BasicTable, useTable, BasicColumn } from '/@/components/Table';
import { Timeline, TimelineItem, Descriptions, Image, } from 'ant-design-vue';
export default defineComponent({
  name: 'detail',
  components: {
    Image,
    BasicTable,
    quoteModel,
    deliveryModal,
    payLogModal,
    takingOrdersModel,
    remarksModal,
    checkModel,
    partsListModal,
    outModal,
    addAccessoryModel,
    Descriptions: Descriptions,
    DescriptionsItem: Descriptions.Item,
    // Timeline: Timeline,
    TimelineItem: TimelineItem,
    [Timeline.name]: Timeline,
    // [Timeline.Item.name]: Timeline.Item,
    PreviewGroup: Image.PreviewGroup,
    reviewModal,
  },
  setup(props) {
    const router = useRouter();
    const { createMessage, createConfirm } = useMessage();
    const { t } = useI18n();
    const permissionStore = usePermissionStore();
    const { getCheckPerm } = permissionStore;
    const repairId = ref<string | string[]>(router.currentRoute.value.params.id || '0');
    const detailData = ref<detailResult>({
      customer: {},
      customerAddress: {},
      repairerVo: {},
      RepairTestVo: {},
      repairRegisterVo: {},
      orderReceivingVo: {},
      repairPay: {},
      RepairComment: {},
      priceList: [],
      lastRepairId: '',
    });
    const priceTotal = ref(0)
    const stepList = ref<any>([]);
    const butList = ref<any>([]);
    onMounted(() => {
      getData();
    });
    let dataSource = reactive<any>([]);
    const columns: BasicColumn[] = [
      {
        title: '备件名称',
        dataIndex: 'name',
        width: 150,
      },
      {
        title: '单价（元）',
        dataIndex: 'price',
        width: 100,
      },
      {
        title: '数量',
        dataIndex: 'count',
        width: 110,
      },
      {
        title: '小计（元）',
        dataIndex: 'total',
        width: 140,
      },
    ];
    async function getData() {
      const stepRes = await process({ repairId: repairId.value });
      let butTypeList = {
        0: ['接单'],
        1: ['检测登记'],
        2: ['报价'],
        3: ['修改报价'],
        4: ['付款登记'],
        5: ['备件出库'],
        6: ['添加备件', '完成维修'],
        7: ['备件回收'],
        8: ['测试登记'],
        9: ['付款登记'],
        10: ['发货登记'],
      };
      let butTypeShow = {
        0: ['work_orderTakers'],
        1: ['maintenance_testing'],
        2: ['work_quotedPrice'],
        3: ['work_setPrice'],
        4: ['work_payments'],
        5: ['repairspares_out'],
        6: ['maintenance_add', 'maintenance_finish'],
        7: ['repairspares_in'],
        8: ['repair_test'],
        9: ['work_payments'],
        10: ['work_dispatched'],
      }
      stepList.value = stepRes;
      let res = await detail({ repairId: repairId.value });
      detailData.value = res;
      let butListjh = [];
      if(stepRes[0] && stepRes[0].haveButton == 1 && res.repairerVo.status != undefined){
        butTypeList[res.repairerVo.status] && butTypeList[res.repairerVo.status].map((ele, index) =>{
          let butKey = butTypeShow[res.repairerVo.status][index]
          if(getCheckPerm(butKey)){
            butListjh.push(ele)
          }
        })
      }
      butList.value = butListjh
      let countItem = {
        id: 3,
        price: null,
        name: '',
        count: '合计（元）',
        total: 0,
      };
      dataSource = res.priceList.map((ele) => {
        let price = ele.discount == 1?ele.priceDiscount:ele.price
        let elePrice = countItem.total + parseFloat(price) * ele.count
        countItem.total = elePrice;
        return {
          // ...ele,
          count: ele.count,
          name: ele.name,
          price: price,
          id: ele.laborId,
          total: (price * ele.count).toFixed(2),
        };
      });
      priceTotal.value = countItem.total?.toFixed(2)
      countItem.total = res.repairerVo.warrantyType == 0?'0.00':priceTotal.value
      let addItemList = [countItem]
      if(res.repairerVo.warrantyType == 0){
        addItemList.unshift({
        id: 4,
        price: null,
        name: '保内维修',
        count: '',
        total: '-'+priceTotal.value,
      })
      }
      if (countItem.total && res.priceList.length) {
        setTableData(cloneDeep([...dataSource, ...addItemList]));
      }
    }
    function goBack() {
      router.go(-1);
    }
    function handleBut(item) {
      console.log('handleBut', item, stepList.value[0].repairStatus);
      let status = detailData.value.repairerVo.status;
      let record = {
        repairId:repairId || detailData.value.orderReceivingVo?.repairId,
        cameraSnCode: detailData.value.repairerVo?.cameraSnCode,
        cameraType: detailData.value.repairerVo?.cameraType,
        status:status,
        payAmount:0,
      };
      if(status == 9 || status == 4){
        record.payAmount = priceTotal.value
      }
      let openList = {
        0: openTakingOrders, //检测登记
        1: openCheckModal, //检测登记
        2: openQuoteModal, //报价
        3: openQuoteModal, //修改报价
        4: openPayLogModal, //付款登记
        5: openPartsModal, //备件出库
        7: openPartsModal, //备件回收
        8: openReviewModal, //测试登记
        9: openPayLogModal, //付款登记
        10: openDeliveryModal, //发货登记
        61: openAddModal, //添加备件
        62: openOutModal, //完成维修
      };
      if(status == 6){
        openList[item == '添加备件'?61:62](true, {
        ...record,
        repairManName: detailData.value.repairRegisterVo?.sysUserName,
      });
      }else{
        openList[status](true, {
        ...record,
        repairManName: detailData.value.repairRegisterVo?.sysUserName,
      });
      }
    }
    function handleSubmit() {
      createMessage.success(t('common.optSuccess'));
    }
    function reload() {
      getData();
    }
    function dowmFile(type){
      let name = type==0?'报价单':'维修工单'
      createConfirm({
        iconType: 'warning',
        title: () => h('span', t('common.reminder')),
        content: () => h('span', `是否导出${name}`),
        onOk: async () => {
          console.log('repairId')
          let apiData = {
            repairId:repairId.value,
            name:repairId.value + name,
            type,
          }
          console.log('apiData',apiData)
          await detailDownExport(apiData);
        },
      });
      
    }
    const [registerParts, { openModal: openPartsModal }] = useModal();
    const [registerReview, { openModal: openReviewModal }] = useModal();
    const [registerRecovery, { openModal }] = useModal();
    const [registerCheck, { openModal:openCheckModal }] = useModal();
    const [registerQuote, { openModal: openQuoteModal }] = useModal();
    const [registerPayLog, { openModal: openPayLogModal }] = useModal();
    const [registerDelivery, { openModal: openDeliveryModal }] = useModal();
    const [registerTakingOrders, { openModal: openTakingOrders }] = useModal();
    const [registerRemarks, { openModal: openRemarksModal }] = useModal();
    // const [registerRecovery, { openModal }] = useModal();
    const [registerOut, { openModal: openOutModal }] = useModal();
    const [registerAdd, { openModal: openAddModal }] = useModal();
    const [registerTable, { setTableData }] = useTable({
      dataSource: dataSource,
      columns,
      showSummary: true,
      showIndexColumn: false,
      rowKey: 'id',
      pagination: false,
      bordered: true,
      canResize: false,
    });
    return {
      repairId,
      registerParts,
      registerReview,
      registerRecovery,
      registerQuote,
      registerPayLog,
      registerDelivery,
      registerTakingOrders,
      registerRemarks,
      registerOut,
      registerCheck,
      registerAdd,
      registerTable,
      handleSubmit,
      goBack,
      handleBut,
      reload,
      detailData,
      butList,
      dataSource,
      stepList,
      dowmFile,
      t,
    };
  },
});
</script>
<style lang="less" scoped>
.detailPage {
  margin: 20px;
  padding: 20px;
  background-color: #fff;
  .topButton {
    text-align: right;
  }
  .htmlText{
      overflow: hidden;
      text-overflow: ellipsis;
      width: 100%;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 3;
      word-break: break-all;
  }
  .content {
    width: 100%;
    display: flex;
    justify-content: space-between;
    
    &_right {
      width: 400px;
      padding: 40px 20px;
      .timeItem{
        .ant-image-img{
          width: 100%;
          height: 100%;
        }
      }
    }
    &_left {
      width: calc(100% - 400px);
    }
  }
  .bottom_but {
    text-align: center;
    button {
      margin: 20px;
    }
  }
  .link{
    color:cornflowerblue;
    cursor: pointer;
  }
}
</style>
<style lang="less">
.detailPage {
  .ellipsis {
    // .ant-descriptions-item-container{
    //   overflow: hidden;
    //   white-space: nowrap;
    //   text-overflow: ellipsis;
    // }
  }
  .ant-image-img{
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}
</style>
