<template>
  <!-- #ifdef H5 -->
  <zj-page-layout :hasFooter="true">
    <view class="all-container">
      <view class="address-container card" @tap="chooseProject">
        <view class="common-title"><text>*</text>项目信息</view>
        <view class="title" v-if="projectInfo">{{projectInfo.projectName}}</view>
        <view class="main">
          <view class="left">
            <view class="icon"><text class="iconfont icon-dingwei1"></text></view>
            <view class="nodata" v-if="!projectInfo">选择联系人地址</view>
            <view class="hasdata" v-else>
              <view class="name">{{projectInfo.manger}}<text>{{projectInfo.mobile}}</text></view>
              <view class="address ellipsis-2">{{projectInfo.province}}{{projectInfo.city}}{{projectInfo.area}}{{projectInfo.street}}{{projectInfo.address}}{{projectInfo.houseNo}}</view>
            </view>
          </view>
          <text class="right iconfont icon-jinru"></text>
        </view>
      </view>

      <view class="service-container card">
        <view class="common-title">服务信息</view>
        <view class="item">
          <view class="label"><text>*</text>工单类型</view>
          <view class="picker" @tap="projectInfo ? isShowOrderTypeDialog = true : $toast('请先选择项目')">
            <text class="value" v-if="orderType">{{orderType.name}}</text>
            <text class="placeholder" v-else>请选择</text>
            <text class="iconfont icon-jinru"></text>
          </view>
        </view>
        <view class="item" v-if="isWorkerUser">
          <view class="label"><text>*</text>服务网点</view>
          <view class="picker" @tap="projectInfo ? isShowWebsitDialog = true : $toast('请先选择项目')">
            <text class="value" v-if="websit">{{websit.websitName}}</text>
            <text class="placeholder" v-else>请选择</text>
            <text class="iconfont icon-jinru"></text>
          </view>
        </view>
        <view class="item">
          <view class="label"><text>*</text>预约上门时间</view>
          <view class="picker" @tap="isShowDatePicker = true">
            <text class="value" v-if="date">{{date}}</text>
            <text class="placeholder" v-else>请选择</text>
            <text class="iconfont icon-jinru"></text>
          </view>
        </view>
      </view>

      <view class="product-container card">
        <view class="title">
          <view class="common-title"><text>*</text>产品信息</view>
          <view class="right" @tap="toChooseProduct"><u-icon name="plus-circle" color="#3D8FFD" size="18"></u-icon>添加</view>
        </view>
        <view class="list">
          <view class="item" v-for="(item, index) in productList" :key="index">
            <image :src="item.imgUrl" mode="aspectFill"></image>
            <view class="main">
              <view class="name">{{item.mainName}} - {{item.smallName}}</view>
              <view class="tags">
                <view class="it">{{item.brandName}}</view>
              </view>
              <u-number-box min="1" v-model="item.num">
                <view slot="minus" class="ctrl">
                  <u-icon name="minus" color="#FFFFFF" size="10"></u-icon>
                </view>
                <text slot="input" class="input">{{item.num}}</text>
                <view slot="plus" class="ctrl">
                  <u-icon name="plus" color="#FFFFFF" size="10"></u-icon>
                </view>
              </u-number-box>
            </view>
            <view class="del" @tap="deleteProduct(item, index)"><text class="iconfont icon-shanchu"></text></view>
          </view>
        </view>
      </view>

      <view class="remark-container card">
        <view class="common-title">备注信息</view>
        <u--textarea v-model="remark" placeholder="请输入内容" border="none" autoHeight></u--textarea>
      </view>
    </view>

    <template slot="footer">
      <view class="footer-btn-group">
      	<u-button text="提交服务单" type="primary" @click="submitData"></u-button>
      </view>
    </template>

    <zjDialogPicker
      ref="orderTypeDialog"
      :isShow="isShowOrderTypeDialog"
      :multiple="false"
      :styleType="2"
      :title="'工单类型'"
      :list="orderTypeList"
      :keyName="'name'"
      @cancel="isShowOrderTypeDialog = false"
      @confirm="confirmOrderTypeDialog">
    </zjDialogPicker>

    <zjDialogPicker
      ref="websitDialog"
      :isShow="isShowWebsitDialog"
      :multiple="false"
      :styleType="2"
      :title="'服务网点'"
      :list="websitList"
      :keyName="'websitName'"
      @cancel="isShowWebsitDialog = false"
      @confirm="confirmWebsitDialog">
    </zjDialogPicker>

    <u-datetime-picker
      :show="isShowDatePicker"
      v-model="datePickerValue"
      mode="date"
      :formatter="formatter"
      @cancel="isShowDatePicker = false"
      @close="isShowDatePicker = false"
      @confirm="confirmDate"
      :minDate="minDate"
    ></u-datetime-picker>
  </zj-page-layout>
  <!-- #endif -->

  <!-- #ifndef H5 -->
  <web-view :src="webViewHref(`/packageHome/pages/maintenance/create`, pam, crossPagePam)" @message="crossPage.$listener"></web-view>
  <!-- #endif -->
</template>

<script>
// #ifdef H5
import zjDialogPicker from "@/components/zj-dialog/zj-dialog-picker.vue";

export default {
  components: {
    zjDialogPicker
  },

  data() {
    return {
      projectInfo: null,
      userInfo: {},
      orderType: null,
      orderTypeList: [],
      isShowOrderTypeDialog: false,
      websit: null,
      websitList: [],
      isShowWebsitDialog: false,
      date: '',
      datePickerValue: Number(new Date()),
      minDate: Number(new Date()),
      isShowDatePicker: false,

      productList: [],

      remark: '',
    }
  },

  computed:{
    isWorkerUser() { // 是否师傅
      return this.userInfo && this.userInfo.type === 'WORKER';
    },
    isLogin() {
      return this.$store.state.user.token ? true : false
    },
  },

  async onLoad({projectId = ''}) {

    this.userInfo = await this.$getUserInfo();

    this.$api.post('/engin/project/repair/list', {
      pageNum: 1,
      pageSize: -1
    }).then(res => {
      if(!res.data.records || res.data.records.length < 1) {
        this.$modal({
          content: '您暂无维保工程',
          showCancel: false
        }).then(() => {
          this.$navToPage({
          	delta: 1
          }, 'navigateBack')
        }).catch(() => {})
      }
    })

    if(projectId) {
      this.$api.post('/engin/project/repair/list', {
        pageNum: 1,
        pageSize: 1,
        id: projectId
      }).then(res => {
        this.projectInfo = res.data.records[0];
        this.orderType = null;
        this.websit = null;
        this.confirmProject();
      })
    }

    // 接收项目信息
    this.crossPage.$on('chooseProject', result => {
      if(result) {
        this.projectInfo = result;
        this.orderType = null;
        this.websit = null;
        this.confirmProject();
      }
    })

    // 接收产品分类
    this.crossPage.$on('chooseClassify', result => {
      let index = this.productList.findIndex((item) => item.smallId == result.smallId && item.brandId == result.brandId);
      if (index !== -1) {
        this.productList.splice(index, 1, result);
      } else {
        this.productList.push(result);
      }
    })
  },

  onUnload() {
    this.crossPage.$off('chooseProject');
    this.crossPage.$off('chooseClassify');
  },

  methods: {

    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`
      }
      if (type === 'month') {
        return `${value}月`
      }
      if (type === 'day') {
        return `${value}日`
      }
      return value
    },

    // 去选择项目
    chooseProject() {
      this.$navToPage({
        url: '/packageHome/pages/maintenance/project'
      })
    },

    // 选择项目后回显内容
    confirmProject() {
      this.$api.post('/engin/project/repair/detail', {
        id: this.projectInfo.id
      }).then(res => {
        let ids = res.data.orderSmallType.split('/');
        let names = res.data.orderSmallTypeText.split('/');
        let orderTypeList = [];
        ids.forEach((item, index) => {
          orderTypeList.push({
            id: ids[index],
            name: names[index],
          })
        })
        this.orderTypeList = orderTypeList;
        if(this.orderTypeList.length === 1) {
          this.orderType = this.orderTypeList[0];
        }

        this.websitList = res.data.projectRepairWebsitList || [];
        if(this.websitList.length === 1) {
          this.websit = this.websitList[0];
        }
      })
    },

    confirmOrderTypeDialog(e) {
      this.orderType = this.orderTypeList[e[0]];
      this.isShowOrderTypeDialog = false;
    },

    confirmWebsitDialog(e) {
      this.websit = this.websitList[e[0]];
      this.isShowWebsitDialog = false;
    },

    toChooseProduct() {
      if(!this.projectInfo) return this.$toast('请选择项目信息');
      this.$navToPage({
        url: `/packageHome/pages/maintenance/product?projectId=${this.projectInfo.id}`
      })
    },

    deleteProduct(item, index) {
      this.$modal({
        content: `确定删除${item.smallName}吗？`
      }).then(() => {
        this.productList.splice(index, 1);
      }).catch(() => {})
    },

    confirmDate(e) {
      this.isShowDatePicker = false;
      let time = new Date(e.value);
      let y = time.getFullYear();
      let m = (time.getMonth()+1) < 10 ? '0' + (time.getMonth()+1) : time.getMonth()+1;
      let d = (time.getDate()) < 10 ? '0' + (time.getDate()) : time.getDate();
      let hh = (time.getHours()) < 10 ? '0' + (time.getHours()) : time.getHours();
      let mm = (time.getMinutes()) < 10 ? '0' + (time.getMinutes()) : time.getMinutes();
      let ss = (time.getSeconds()) < 10 ? '0' + (time.getSeconds()) : time.getSeconds();
      this.date = `${y}-${m}-${d}`;
    },

    submitData() {
      if(!this.projectInfo) return this.$toast('请选择项目信息');
      if(!this.orderType) return this.$toast('请选择工单类型');
      if(!this.websit && this.isWorkerUser) return this.$toast('请选择服务网点');
      if(!this.date) return this.$toast('请选择预约上门时间');
      if(this.productList.length < 1) return this.$toast('请添加产品信息');

      this.$api.postJson('/pg/order/base/save', {
        orderSmallType: this.orderType.id,
        rpProjectRepairId: this.projectInfo.id,
        websitId: this.websit ? this.websit.websitId : '',
        appointmentTime: this.date + ' 00:00:00',
        orderProducts: this.productList,
        remark: this.remark,
      }).then(res => {
        this.$successToast();
        setTimeout(() => {
          if(this.isWorkerUser) {
            this.$navToPage({
              url: `/packageWorkorder/pages/orderList`
            }, 'redirectTo')
          }else {
            this.$navToPage({
              url: `/packageWorkorder/pages/userWorkorderList`
            })
          }
        }, 500)
      })
    },
  },
}

// #endif
// #ifndef H5
export default {
  data() {
    return {
      pam: {},
    }
  },
  onLoad(pam) {
    this.pam = pam;
  }
}
// #endif
</script>

<style lang="scss" scoped>
.card {
  @include zj-card;
  margin-top: 20rpx;
  padding: 30rpx;
}
.common-title {
  font-size: 32rpx;
  font-weight: 500;
  text {
    color: $error-color;
    font-weight: normal;
  }
}
.all-container {
  padding: 0 20rpx;
}
.address-container {
  .title {
    margin-top: 30rpx;
    font-weight: 500;
  }
  .main {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20rpx;
  }
  .right {
    font-size: 32rpx;
    color: $sec-font;
    flex-shrink: 0;
  }
  .left {
    display: flex;
    align-items: center;
    margin-right: 20rpx;
    .icon {
      width: 52rpx;
      height: 52rpx;
      border-radius: 50%;
      background: $theme-color;
      display: flex;
      flex-shrink: 0;
      justify-content: center;
      align-items: center;
      margin-right: 20rpx;
      .iconfont {
        font-size: 36rpx;
        color: #ffffff;
      }
    }
    .nodata {
      font-size: 28rpx;
      color: #999999;
    }
    .hasdata {
      .name {
        font-size: 32rpx;
        color: #333333;
        text {
          color: #999999;
          font-size: 28rpx;
          margin-left: 16rpx;
        }
      }
      .address {
        font-size: 28rpx;
        color: #666666;
        line-height: 34rpx;
        margin-top: 10rpx;
      }
    }
  }
}
.service-container {
  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 50rpx;
    margin-top: 30rpx;
    .label {
      margin-right: 30rpx;
      text {
        color: $error-color;
      }
    }
    .picker {
      .placeholder {
        color: $sec-font;
      }
      .iconfont {
        margin-left: 12rpx;
        color: $sec-font;
      }
    }
  }
}
.product-container {
  .title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .right {
      color: $theme-color;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      ::v-deep .u-icon {
        margin-right: 8rpx;
      }
    }
  }
  .list {
    .item {
      padding: 30rpx 0;
      border-bottom: 1px solid #eaeaea;
      display: flex;
      &:last-child {
        border: none;
      }
      image {
        width: 100rpx;
        height: 100rpx;
      }
      .main {
        flex: 1;
        margin-left: 20rpx;
        margin-right: 20rpx;
        .name {
          font-size: 28rpx;
          font-weight: 500;
          line-height: 36rpx;
        }
        .tags {
          display: flex;
          margin-top: 12rpx;
          margin-bottom: 16rpx;
          .it {
            font-size: 24rpx;
            color: $theme-color;
            background: rgba($color: $theme-color, $alpha: .3);
            padding: 8rpx 12rpx;
            border-radius: 8rpx;
          }
        }
        .input {
          width: 30rpx;
          text-align: center;
          padding: 0 10px;
        }
        .ctrl {
          width: 36rpx;
          height: 36rpx;
          background-color: $theme-color;
          border-radius: 50%;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
      .del {
        text {
          font-size: 36rpx;
          color: $sec-font;
        }
      }
    }
  }
}
.remark-container {
  ::v-deep .u-textarea {
    margin-top: 20rpx;
    padding: 20rpx 20rpx;
    min-height: 200rpx;
    background: #f5f5f5;
  }
}
</style>
