<template>
  <view class="apply-credit">
    <view class="title">{{$t('approval.formInfo')}}</view>
    <view class="form-wrap">
      <u-form labelPosition="left" :model="form" :rules="rules" ref="form1" labelWidth='90'>
        <!-- 登记日期 -->
        <u-form-item :label="$t('spare.djDate')" borderBottom prop="setDate" @click="showSetDateCalendar = true" required>
          <u-input readonly v-model="form.setDate" border="none" :placeholder="$t('base.common.placeholderS')+$t('spare.djDate')" />
        </u-form-item>
        <!-- 入库 -->
        <template v-if="work == 'in'">
          <!-- 入库单号 -->
          <u-form-item :label="$t('spare.RKCode')" borderBottom prop="code" required>
            <u-input readonly v-model="form.code" border="none" :placeholder="$t('base.common.placeholderI')+$t('spare.RKCode')" />
          </u-form-item>
          <!-- 仓库 -->
          <u-form-item :label="$t('spare.store')" borderBottom prop="store" @click="showPopup('store')" required >
            <u-input readonly v-model="textForm.store" :placeholder="$t('base.common.placeholderS')+$t('spare.store')" border="none" />
          </u-form-item>
          <!-- 供应商 -->
          <u-form-item :label="$t('order.purveyId')" borderBottom prop="purveyId" @click="showPopup('purveyId')" required>
            <u-input readonly v-model="textForm.purveyId" border="none" :placeholder="$t('base.common.placeholderS')+$t('order.purveyId')" />
          </u-form-item>
          <!-- 采购员 -->
          <u-form-item :label="$t('spare.buyer')" borderBottom prop="buyer" @click="showPopup('buyer')">
            <u-input readonly v-model="textForm.buyer" border="none" :placeholder="$t('base.common.placeholderS')+$t('spare.buyer')" />
          </u-form-item>
          <!-- 送货单号 -->
          <u-form-item :label="$t('spare.delivery')" borderBottom prop="delivery">
            <u-input :readonly="type == 'view'" v-model="form.delivery" border="none" :placeholder="$t('base.common.placeholderI')+$t('spare.delivery')" />
          </u-form-item>
          <!-- 入库明细 -->
          <u-form-item :label="$t('spare.inStoreDetail')" borderBottom prop="detailList" @click="toAddDetail" v-if="type != 'view'">
            <u-input readonly border="none" :placeholder="$t('spare.setInStoreDetail')" />
            <u-icon
              slot="right"
              name="arrow-right"
            ></u-icon>
          </u-form-item>
          <!-- 用途 -->
          <u-form-item :label="$t('spare.purpose')" borderBottom prop="purpose">
            <u-input 
            :readonly="type == 'view'"
             v-model="form.purpose" 
             border="none" 
             :placeholder="$t('base.common.placeholderI')+$t('spare.purpose')" />
          </u-form-item>
        </template>

        <!-- 出库 -->
        <template v-else>
          <!-- 入库单号 -->
          <u-form-item :label="$t('spare.CKCode')" borderBottom prop="code" required>
            <u-input readonly v-model="form.code" border="none" :placeholder="$t('base.common.placeholderI')+$t('spare.CKCode')" />
          </u-form-item>
          <!-- 仓库 -->
          <u-form-item :label="$t('spare.store')" borderBottom prop="store" @click="showPopup('store')" required >
            <u-input readonly v-model="textForm.store" :placeholder="$t('base.common.placeholderS')+$t('spare.store')" border="none" />
          </u-form-item>
          <!-- 部门 -->
          <u-form-item :label="$t('userinfo.department')" borderBottom prop="department" @click="showPopup('department')" required>
            <u-input readonly v-model="textForm.department" border="none" :placeholder="$t('base.common.placeholderS')+$t('userinfo.department')" />
          </u-form-item>
          <!-- 领料人 -->
          <u-form-item :label="$t('spare.takeUser')" borderBottom prop="requester" @click="showPopup('requester')">
            <u-input readonly v-model="textForm.requester" border="none" :placeholder="$t('base.common.placeholderS')+$t('spare.takeUser')" />
          </u-form-item>
          <!-- 出库明细 -->
          <u-form-item :label="$t('spare.outStoreDetail')" borderBottom prop="detailList" @click="toAddDetail" v-if="type != 'view'">
            <u-input readonly border="none" :placeholder="$t('spare.outStoreDetail')" />
            <u-icon
              slot="right"
              name="arrow-right"
            ></u-icon>
          </u-form-item>
        </template>
        <!-- 备注 -->
        <u-form-item :label="$t('approval.remark')" borderBottom prop="remark">
          <u-input :readonly="type == 'view'" v-model="form.remark" border="none" :placeholder="$t('approval.remark')" />
        </u-form-item>
      </u-form>
    </view>
    <view class="title">{{work == 'in'?$t('spare.inStoreDetail'):$t('spare.outStoreDetail')}}</view>
      <template v-if="form.detailList.length">
         <view class="order-card" v-for="(item, index) in form.detailList" :key="index">
          <view class="order-info">
            <p class="info-line">
              <text class="label">{{$t('spare.spareName')}}:</text>
              <text class="info">
                <template v-if="id || item.sourceType == '101'">
                  {{`${item.materialCode}_${item.materialName}_${item.materialSpec}_${getLabel(item.materialUnit,unitList)}`}}
                </template>
                <template v-else>
                  {{`${item.code}_${item.name}_${item.spec}_${getLabel(item.unit,unitList)}`}}
                </template>
              </text>
            </p>
            <!-- 入库 -->
            <template v-if="work == 'in'">
              <p class="info-line">
                <text class="label">{{$t('spare.source')}}</text>
                <text class="info">{{item.sourceType == '102'?$t('spare.batchAdd'):$t('mine.order')+item.orderCode}}</text>
              </p>
              <p class="info-line">
                <text class="label">{{$t('spare.inStoreNumber')}}:</text>
                <text class="info">{{item.count || ''}}</text>
              </p>
              <p class="info-line">
                <text class="label">{{$t('spare.shelf')}}:</text>
                <u-icon class="info" name="list" size="30" @click="openShelf(item)" color="#2979ff"></u-icon>
              </p>
              <p class="info-line">
                <text class="label">{{$t('approval.remark')}}:</text>
                <text class="info">{{item.remark || ''}}</text>
              </p>
            </template>
              <!-- 出库 -->
            <template v-else>
              <p class="info-line">
                <text class="label">{{$t('spare.source')}}:</text>
                <text class="info">{{item.sourceType == '102'?$t('spare.batchAdd'):$t('mine.order')+':'+item.takeCode}}</text>
              </p>
              <p class="info-line">
                <text class="label">{{$t('spare.canOutNumber')}}:</text>
                <text class="info">
                  {{item.sourceType == '101'?(item.number - item.outNum):item.totalNum}}
                </text>
              </p>
              <p class="info-line">
                <text class="label">{{$t('spare.outStoreNumber')}}:</text>
                <text class="info">{{item.count || ''}}</text>
              </p>
              <p class="info-line">
                <text class="label">{{$t('spare.shelf')}}:</text>
                <u-icon class="info" name="list" size="30" @click="openShelf(item)" color="#2979ff"></u-icon>
              </p>
              <p class="info-line">
                <text class="label">{{$t('approval.remark')}}:</text>
                <u-input class="info" suffixIcon="edit-pen"  :placeholder="$t('approval.remark')" border="none" v-model="item.remark" />
              </p>
            </template>
          </view>
        </view>
      </template>
      <template v-else>
        <u-empty mode="list" :text="$t('spare.setBuyDetail')" icon="https://cdn.uviewui.com/uview/empty/list.png">
        </u-empty>
      </template>
    <view class="btn-wrap"  v-if="type != 'view'">
      <u-button type="primary" color='#4680F9' @click="submit('form1')">{{$t('base.common.submit')}}</u-button>
    </view>
    <!-- 仓库 -->
    <PopupSelect ref="store" kind="store" :option="storeOptions" @onConfirm="onConfirm"/>
    <!-- 供应商 -->
    <PopupSelect ref="purveyId" kind="purveyId" :option="purveyIdOptions" @onConfirm="onConfirm"/>
    <!-- 部门 -->
    <PopupSelect ref="department" kind="department" :option="departmentOptions" @onConfirm="onConfirm"/>
    <!-- 领料人 -->
    <PopupSelect ref="requester" kind="requester" :option="requesterOptions" @onConfirm="onConfirm"/>
     <!-- 采购员 -->
    <PopupSelect ref="buyer" kind="buyer" :option="buyerOptions" @onConfirm="onConfirm"/>
    <!-- 申请日期 -->
    <u-calendar 
    color="#4680F9" 
    round='25' 
    :show="showSetDateCalendar" 
    @confirm="onSetDateConfirm" 
    @close="showSetDateCalendar=false">
    </u-calendar>
    <u-toast ref="loadingToast" />
    <!-- 货架 -->
    <u-popup :show="shelfShow" mode="center"  @close="shelfShow = false" >
      <view class="picker-card">
        <view style="height:100%;overflow-y:auto;display:block">
          <view class="order-card shelf-card" v-for="(item, index) in currentRow.shelfList" :key="index">
            <view class="order-info">
              <p class="info-line">
                <text class="label">{{$t('spare.shelf')}}:</text>
              <text class="info">{{item.shelf}}</text>
              </p>
              <p class="info-line">
                <text class="label">{{$t('spare.floor')}}:</text>
              <text class="info">{{item.floor}}</text>
              </p>
              <p class="info-line">
                <text class="label">{{$t('spare.seat')}}:</text>
              <text class="info">{{item.seat}}</text>
              </p>
              <p class="info-line">
                <text class="label">{{$t('spare.sign')}}:</text>
              <text class="info">{{item.sign}}</text>
              </p>
              <p class="info-line">
                <text class="label">{{$t('spare.number')}}:</text>
                <text class="info">{{item.num}}</text>
              </p>
            </view>
          </view>
        </view>
        <view class="card-oper">
          <view class="btn">
            <u-button type='primary' @click="shelfShow = false">{{$t('settings.confirmText')}}</u-button>
          </view>
        </view>
      </view>
	  </u-popup>
  </view>
</template>

<script>
import PopupSelect from '../../components/popup-select/index'
import { getObj,getStockStore,addObj } from '../../api/warehousing'
import { getLabel } from '../../utils/util'
import {request} from '../../utils/request'
import { fetchList,depLtist } from '../../api/stock'
import dayjs from 'dayjs'
import {
  getCode,
  getClientList,
  getUserListByType
} from "../../api/receivable"
export default {
  components:{
    PopupSelect
  },
  data(){
    return{
      id:'', 
      type:'', //类型 add新增/edit编辑/view查看
      work:'', //in 入库 out 出库
      showSetDateCalendar:false,
      shelfShow:false,
      getLabel,
      currentRow:{},
      form:{
        setDate:dayjs().format('YYYY-MM-DD'),
        code:'',
        store:'', //仓库
        purveyId:'', //供应商
        buyer:'', //采购员
        delivery:'', //送货单
        purpose:'', //用途
        requester:'', //申请人
        department:'', //部门
        kind:'11',
        detailList:[],
        remark:'',
      },
      textForm:{
        store:'',
        purveyId: '',
        buyer:'',
      },
      rules: {
        setDate:[{ required: true, message: this.$t('base.common.placeholderS')+'登记日期', trigger: "change" }],
        store:[{ required: true, message: this.$t('base.common.placeholderS')+'仓库', trigger: "change" }],
        purveyId:[{ required: true, message: this.$t('base.common.placeholderS')+this.$t('order.purveyId'), trigger: "change" }],
        code:[{ required: true, message:this.$t('base.common.placeholderS')+this.$t('spare.orderCode'), trigger: "change" }],
        department:[{ required: true, message:this.$t('base.common.placeholderS')+this.$t('spare.orderCode'), trigger: "change" }],
        detailList:[{
          required: true,
          validator:(rule,value,callback)=>{
            if(this.form.detailList.length){
              callback()
            }else{
              callback(new Error("入库明细不能为空"))
            }
          }
        }],
      },
      purveyIdOptions:[{text:this.$t('order.noData'),value:null}],
      buyerOptions:[{text:this.$t('order.noData'),value:null}],
      storeOptions:[{text:this.$t('order.noData'),value:null}],
      departmentOptions:[{text:this.$t('order.noData'),value:null}],
      requesterOptions:[{text:this.$t('order.noData'),value:null}],
      unitList:[],
    }
  },
  onLoad(options) {
    console.log(options);
    this.id = options.id
    this.type = options.type
    this.work = options.work
    if(this.work == 'in'){
      this.form.kind ='11'
    }else{
      this.form.kind ='14'
    }
    this.setPageTitle()
    this.getOption()
  },
  methods:{
    //提交审批
    submit(ref){
      let _this=this
      this.$refs[ref].validate().then(() => {
        this.$refs.loadingToast.show({
          type:"loading",
          message: _this.$t('base.common.loading'),
          duration:'100000',
				})
        let data
        if(_this.work == 'in'){
          data = _this.form
        }else{
          _this.form.detailList = _this.form.detailList.map(item=>{
            item.shelfList = item.materialShelves
            return item
          })
          data = _this.form
        }
        addObj(data).then(res=>{
          if(res.data.code == 0){
            this.$refs.loadingToast.hide()
            uni.showModal({
              title: _this.$t('settings.tips'),
              content:  _this.$t('spare.submitSuccess'),
              showCancel: false,
              success: ({ confirm, cancel }) => {
                if(confirm){
                  uni.navigateBack({ delta: 1 })
                }
              }
            })
          }else{
            this.$refs.loadingToast.hide()
            uni.showModal({
              title: _this.$t('settings.tips'),
              content: res.data.msg || _this.$t('spare.submitfailed'),
              showCancel: false,
            })
          }
        })
      })
    },
    //查看或编辑获取详情
    getDetail(){
      getObj(this.id).then(res=>{
        if(res.data.code == 0){
          Object.keys(this.form).forEach((key) => {
            this.form[key] = res.data.data[key]
          })
          this.textForm.store = res.data.data.storeName
          this.textForm.purveyId = res.data.data.purveyName
          this.textForm.buyerName = res.data.data.buyerName
        }
      })
    },
    //打开货架
    openShelf(item){
      console.log(item);
      this.currentRow = item
      this.shelfShow = true
    },  
    //获取选项
    getOption(){
      //获取单位
      request({
        url:'/admin/dict/type/spare_unit',
        method:'get',
      })
      .then(res=>{
        if(res.data.code == 0){
          this.unitList = res.data.data
        }
      })
      //订单编码
      if(this.type == 'add'){
        getCode(this.work == 'in'?'118':'120',dayjs().format('YYYY-MM-DD')).then(res=>{
          if(res.data.code == 0){
            this.form.code = res.data.data
          }
        })
      }
      if(this.work == 'in'){
        //获取供应商
        getClientList( {type:'103'}).then(res=>{
          if(res.data.code == 0){
            let arr=[]
            res.data.data.forEach(item=>{
              arr.push({
                text:item.name,
                value:item.id
              })
            })
            if(arr.length){
              arr.unshift({text:this.$t('order.notSelected'),value:null})
            }else{
              arr.unshift({text:this.$t('order.noData'),value:null})
            }
            this.purveyIdOptions = arr
          }
        })
        //获取采购员
        getUserListByType('101').then(res=>{
          let arr=[]
          res.data.data.forEach(item=>{
            arr.push({
              text:item.name,
              value:item.userId
            })
          })
          if(arr.length){
            arr.unshift({text:this.$t('order.notSelected'),value:null})
          }else{
            arr.unshift({text:this.$t('order.noData'),value:null})
          }
          this.buyerOptions = arr
        })
      }else if(this.work == 'out'){
        //获取部门
      depLtist().then(res=>{
        let arr=res.data.data.map(item=>{
          return {
            text:item.name,
            value:item.deptId
          }
        })
        if(arr.length){
          arr.unshift({text:this.$t('order.notSelected'),value:null})
        }else{
          arr.unshift({text:this.$t('order.noData'),value:null})
        }
        this.departmentOptions=arr
      })
      }
      
      //获取仓库
      getStockStore('').then(res=>{
        if(res.data.code == 0){
          let arr=[]
          res.data.data.forEach(item=>{
            arr.push({
              text:item.name,
              value:item.id
            })
          })
          if(arr.length){
            arr.unshift({text:this.$t('order.notSelected'),value:null})
          }else{
            arr.unshift({text:this.$t('order.noData'),value:null})
          }
          this.storeOptions = arr
        }
      })
      
    },
    //切换选择部门
    changeDept(id){
      let data = {
        size:50,
        current:1,
        deptId:id,
      }
      fetchList(data).then(res=>{
        let arr = res.data.data.records.map(j=>{
          return {
            text:j.name,
            value:j.userId,
          }
        })
        console.log(arr);
        if(arr.length){
          arr.unshift({text:this.$t('order.notSelected'),value:null})
        }else{
          arr.unshift({text:this.$t('order.noData'),value:null})
        }
        this.requesterOptions = arr
      })
    },
    //去添加明细
    toAddDetail(){
      let _this = this
      if(this.work == 'in'){
        if(this.form.purveyId){
          uni.navigateTo({ url: `/subpages/spare/choosespare?purveyId=${this.form.purveyId}&work=in&content=${JSON.stringify(this.form.detailList)}`})
        }else{
          uni.showModal({
            title: _this.$t('settings.tips'),
            content: _this.$t('base.common.placeholderS')+_this.$t('order.purveyId'),
            showCancel: false,
            success: ({ confirm, cancel }) => {
              
            }
          })
        }
      }else{
        if(this.form.department && this.form.store){
          uni.navigateTo({ url: `/subpages/spare/choosespare?dept=${this.form.department}&work=out&content=${JSON.stringify(this.form.detailList)}`})
        }else{
          uni.showModal({
            title: _this.$t('settings.tips'),
            content: '请先选择仓库和部门',
            showCancel: false,
            success: ({ confirm, cancel }) => {
              
            }
          })
        }
      }
      
    },
    //确定选择
    onConfirm(value,kind){
      if(kind == 'department' && value.value != this.form[kind]){
        this.changeDept(value.value)
      }
      if(value.value){
        this.form[kind]=value.value
        this.textForm[kind]=value.text
      }else{
        this.form[kind]=''
        this.textForm[kind]=''
      }
    },
    //选择申请日期
    onSetDateConfirm(date){
      this.form.setDate = dayjs(date).format('YYYY-MM-DD');
      this.showSetDateCalendar = false;
    },
    //设置页面标题
    setPageTitle(){
      let str=''
      if(this.work == 'in'){
        str+='入库'
      }else{
        str+='出库'
      }
      if(this.type == 'add'){
        str+='新增'
      }else if(this.type == 'edit'){
        this.getDetail()
        str+='编辑'
      }else if(this.type == 'view'){
        this.getDetail()
        str+='查看'
      }
      uni.setNavigationBarTitle({
        title: str
      });
    },
    //显示选择
    showPopup(refs){
      if(this.type == 'view'){
        return
      }
      this.$refs[refs].showPicker=true
    },
  }
}
</script>

<style lang="scss" scoped>
@import '../../common/css/apply.scss';
.order-card{
  position: relative;
  box-shadow:0 0 16rpx 0px rgba(0, 0, 0, 0.1);
  // background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  // margin-top: 24rpx;
  margin: 24rpx 24rpx 0;
  z-index: 50;
  display: block;
    
  .order-card-title{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    // background: linear-gradient(to right, rgb(245, 249, 255), #fff);
    padding: 16rpx 24rpx;
    line-height: 50rpx;
    font-size: 32rpx;
    font-weight: 600;
    color: #fff;
    box-shadow:0 0 16rpx 0px rgba(0, 0, 0, 0.1);
}
  
  .order-info {
    background-color: #fff;
    font-size: 28rpx;
    line-height: 56rpx;
    padding: 24rpx;
    color: #333;
    position: relative;
    .info-line {
      display: flex;
      flex-direction: row;
      align-items: center;
      line-height: 72rpx;
      .label {
        width: 200rpx;
        text-align: center;
        font-size: 24rpx;
      }
      .info {
        flex: 1;
        font-weight: bold;
        font-size: 28rpx;
      }
      .tag{
        padding: 0 16rpx 0 12rpx;
        border-top-right-radius: 40rpx;
        border-bottom-right-radius: 40rpx;
        height: 40rpx;
        line-height: 40rpx;
      }
      .tag-ls{
        border: 1px solid #f9ae3d;
        background-color: #fdf6ec;
        color: #f9ae3d;
      }
      .tag-gd{
        border: 1px solid #3c9cff;
        background-color: #ecf5ff;
        color: #3c9cff;
      }
      .tag-gx{
        border: 1px solid #5ac725;
        background-color: #f5fff0;
        color: #5ac725;
      }
    }
    .qrcode-logo{
      position: absolute;
      width: 128rpx;
      height: 128rpx;
      bottom: 24rpx;
      right: 24rpx;
      .img{
        width: 100%;
        height: 100%;
      }
    }
  }
  .card-oper{
    background-color: #fff;
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    padding: 24rpx;
    .btn{
      width: 25%;
      margin-left: 32rpx;
    }
  }
}
.shelf-card{
  margin: 0 0 24rpx; 
  display: block;
  .order-info{
    flex-direction: row;
    flex-wrap: wrap;
    .info-line{
      width: 50%;
      .label{
        width: 120rpx;
      }
    }
  }
}
// /deep/ .u-popup__content{
//   height: 70%;
//   width: 90%;
//   overflow-y: scroll;
//   border-radius: 6px;
//   background-color: #f8f8f8;
// }
.picker-card{
    padding: 32rpx 32rpx 144rpx;
    position: relative;
    height: 100%;
    overflow-y: scroll;
    display: block;
    .card-oper{
      position: absolute;
      width: 100%;
      bottom: 0;
      left:0;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      padding: 24rpx;
      .btn{
        width: 100%;
      }
    }
  }
</style>