<template>
    <div class="ScanSign" data-key="SCAN_QIANSHOU"> 
      <div style="margin-bottom: 10px;">
        <span class='partTitle'>扫描项</span>
        <Form
          ref="formInline"
          :model="formInline"
          :rules="ruleValidate"
          :label-width="110"
          inline>
          <Row type="flex" justify="start">
            <Col span="12">
              <FormItem label="物流公司" prop="COMPANY">
                <Select
                  v-model="formInline.COMPANY.value"
                  @on-change="chooseCompany"
                  label-in-value>
                    <Option
                      v-for="item in expressList"
                      :key="item.value"
                      :value="item.value">
                      {{ item.label }}
                    </Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="物流单号" prop="DISPATCHNO">
                <Input
                  autofocus
                  v-model="formInline.DISPATCHNO"
                  @on-enter="submitDISPATCHNO" />
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="签收仓库" prop="STOREID">
                  <Select
                    v-model="formInline.STOREID.value"
                    @on-change="chooseWarehouse"
                    label-in-value>
                      <Option
                        v-for="item in warehouseList"
                        :key="item.value"
                        :value="item.value">
                        {{ item.label }}
                      </Option>
                  </Select>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="手机号">
                <Input v-model="formInline.MOBILE" />
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="发货地址">
                <Input v-model="formInline.SELLADDRESS" />
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="品牌" prop="BRAND">
                <Select
                  v-model="formInline.BRAND"
                  @on-change="(value) => commonChooseHandle({ type: 'BRAND', value })">
                    <Option
                      v-for="item in brandList"
                      :key="item.value"
                      :value="item.value">
                      {{ item.label }}
                    </Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="签收原因" prop="ERECEIPT_CAUSE">
                <Select
                  v-model="formInline.ERECEIPT_CAUSE"
                  @on-change="(value) => commonChooseHandle({ type: 'ERECEIPT_CAUSE', value })">
                    <Option
                      v-for="item in receiveResons"
                      :key="item.value"
                      :value="item.value">
                      {{ item.label }}
                    </Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="备注">
                <Input v-model="formInline.DESCRIPTION" />
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="是否扫描SKU">
                <Select
                  v-model="formInline.SCANSKUFLAG"
                  @on-change="chooseSCANSKUFLAG">
                  <Option
                    v-for="item in ScanSKUOptions"
                    :key="item.value"
                    :value="item.value">
                    {{ item.label }}
                  </Option>
                </Select>
              </FormItem>
            </Col>
            <Col span="12" v-if="formInline.SCANSKUFLAG == 2">
              <FormItem label="SKU">
                <Input
                  ref="SCANSKU"
                  v-model="formInline.SKU"
                  @on-enter="selectSkuGoods" />
              </FormItem>
            </Col>
          </Row>
        </Form>
      </div>
      <div style="margin-bottom: 10px;" v-if="ScanSKUData.length>0">
        <span class='partTitle'>商品扫描记录</span>
        <Table
          class='ScanSKUTable'
          :columns="ScanSKUColumns"
          :data="ScanSKUData"
          height="150"
          highlight-row></Table>
      </div>
      <div style="margin-bottom: 10px;" > 
         <!-- v-if="ScanSignCount > 0" -->
        <p class="countAll">本次已扫描签收{{ ScanSignCount }}单</p>
      </div>
      <div class="bottomBtnBox">
        <Button
          :loading="loading"
          type="primary"
          size="small"
          class="sureBtn"
          @click="ScanSign">提交</Button>
        <Button
          size="small"
          class="cancelBtn"
          ghost
          @click="cancel">取消</Button>
      </div>
      <!-- 扫描声音播放 -->
      <video
        id="audio"
        style="display: none;" />
      <!-- 扫描物流单声音播放 -->
      <video
        id="order-audio"
        style="display: none;" />
      <Spin fix v-if="Spinloading">
        <div class="loader">
          <svg class="circular" viewBox="25 25 50 50">
            <circle class="path" cx="50" cy="50" r="20" fill="none" stroke-width="5" stroke-miterlimit="10"></circle>
          </svg>
        </div>
        <div>操作中...</div>
      </Spin>
    </div>
  </template>
  
  
  <script>
  import dayjs from 'dayjs';
    const R3 = window.R3;
  
    const { network, urlSearchParams } = R3;
    export default {
      props: {
        selectRowData: {// 获取ID用于多选,获取勾选的明细对应的row内的数据
          type: [Array, Object],
          default: () => {}
        }
      },
      data() {
        return {
          ScanSignCount: 0, //已扫描签收数量
          formInline: {
            COMPANY: {
              value: '',
              label: ''
            },
            DISPATCHNO: '',
            STOREID: {
              value: '',
              label: ''
            },
            MOBILE: '',
            SELLADDRESS: '',
            BRAND: '',
            ERECEIPT_CAUSE: '',
            DESCRIPTION: '',
            SCANSKUFLAG: '',
            SKU: '', 
          },
          ruleValidate: {
            COMPANY: [
              { required: true }
            ],
            DISPATCHNO: [
              { required: true, message: '物流单号不能为空', trigger: 'blur' },
            ],
            STOREID: [
              { required: true }
            ],
          },
          expressList: [], // 物流公司列表
          warehouseList: [], // 签收仓库列表
          brandList: [], // 品牌
          receiveResons: [],//  签收原因下拉框列表
          ScanSKUOptions:[ //是否赠品
            {
              label: '否',
              value: 1
            },
            {
              label: '是',
              value: 2
            },
          ],
          loading: false,
          Spinloading: false,
          columnsKey: ['SHOPTITLE'],
          hidecolumns: ['id', 'PLATFORM', 'value'],
          platform: '', // 平台id
          ScanSKUColumns: [
            {
              title: 'SKU',
              align: 'center',
              key: 'sku'
            },
            {
              title: '数量',
              align: 'center',
              key: 'num',
              render: (h, params) => {
                  return h(
                    'Input',
                    {
                      style: {
                        width:'40px',
                        height: '30px'
                      },
                      props: {
                        value: params.row.num,
                        number: true
                      },
                      on: {
                        'on-blur': (event) => {
                          if(isNaN(event.target.value)){
                            event.target.value=1
                          }else {
                            this.ScanSKUData[params.index].num = event.target.value
                          }
                        }
                      }
                    },
                  );
                },
            },
          ],
          ScanSKUData:[
            // {
            //   SKU: 'TEST001',
            //   NUM: 1
            // }
          ],
          scanError: '', // 扫描失败声音
          scanOrder: '', // 扫描商品声音
          scanOk: '', // 提示声音
          success: '', // 入库成功声音
          scanLogistics: '', // 扫描物流单号声音
        };
      },
      created() {
        this.getPrintSound();
        this.judgeScanSignDate();
        this.getExpressList();
        this.getWarehouseList();
        this.getBrandList();
        this.getReceiveReason();
      },
      // watch: {
      //   formInline(val) {
      //     this.updateScanSignDate();
      //   },
      // },
      methods: {
        // 判断是否当日操作，是否沿用上次选择项数据
        judgeScanSignDate() {
          const localData = localStorage.getItem('ScanSignDate') ? JSON.parse(localStorage.getItem('ScanSignDate')) : [];
          const userId = JSON.parse(localStorage.getItem('userInfo')).id;
          // 从本地缓存里查当前用户的数据
          const userDataIndex = localData.findIndex(item => item.id === userId && item.ScanSignSet);
          // 如果本地存在当前用户的数据
          if (userDataIndex > -1) {
            // 判断缓存是否过期。不是同一天就视为过期
            const localTime = dayjs(localData[userDataIndex].time);
            const todayTime = dayjs(new Date());
            const isSameDay = todayTime.isSame(localTime, 'day');
            if (!isSameDay) {
              this.formInline.COMPANY = {
                value: '',
                label: ''
              }
              this.formInline.STOREID = {
                value: '',
                label: ''
              }
              this.formInline.SCANSKUFLAG = 1
              this.updateScanSignDate()
            }else {
              this.formInline.COMPANY = localData[0].ScanSignSet.COMPANY
              this.formInline.STOREID = localData[0].ScanSignSet.STOREID
              this.formInline.SCANSKUFLAG = localData[0].ScanSignSet.SCANSKUFLAG
            }
          } else {
              this.formInline.COMPANY = {
                value: '',
                label: ''
              }
              this.formInline.STOREID = {
                value: '',
                label: ''
              }
            this.formInline.SCANSKUFLAG = 1
            this.updateScanSignDate()
          }
        },
        // 更新本地缓存的选择项数据
        updateScanSignDate() {
          // this.formInline=JSON.parse(JSON.stringify(this.formInline))
          const localData = localStorage.getItem('ScanSignDate') ? JSON.parse(localStorage.getItem('ScanSignDate')) : [];
          
          const userId = JSON.parse(localStorage.getItem('userInfo')).id
          // 从本地缓存里查当前用户的仓库
          const userDataIndex = localData.findIndex(item => {
            return item.id === userId && item.ScanSignSet
          })
          // 如果有当前用户的数据，则更新缓存
          if (userDataIndex > -1) {
            const newCache = {
              id: userId,
              ScanSignSet: {
                COMPANY: this.formInline.COMPANY,
                STOREID: this.formInline.STOREID,
                SCANSKUFLAG: this.formInline.SCANSKUFLAG
              },
              time: new Date().getTime()
            }
            localData[userDataIndex] = newCache
            localStorage.setItem('ScanSignDate', JSON.stringify(localData));
          } else {
            const newCache = {
              id: userId,
              ScanSignSet: {
                COMPANY: this.formInline.COMPANY,
                STOREID: this.formInline.STOREID,
                SCANSKUFLAG: this.formInline.SCANSKUFLAG
              },
              time: new Date().getTime()
            }
            localStorage.setItem('ScanSignDate', JSON.stringify([newCache]));
          }
        },
        chooseCompany(e) {
          this.formInline.COMPANY = e
          this.updateScanSignDate();
        },
        chooseWarehouse(e) {
          this.formInline.STOREID = e
          this.updateScanSignDate();
        },
        chooseSCANSKUFLAG(e) {
          this.formInline.SCANSKUFLAG = e
          this.updateScanSignDate();
        },
        /**
         * 下拉框多选公用 type区分
         * @param {*} option 
         */
        commonChooseHandle(option) {
          const { type, value } = option;
          this.formInline[type] = value;
          // console.log(this.formInline, 'this.formInline')
        },
        // 查询物流公司
        getExpressList() {
            let params = { 
                table: 'T_V_OMSLOGISTICSCOMPANY',
                range: 1000,
                fixedcolumns: { IsActive: '=Y' } 
            };
            network.post('/p/cs/list/query', params).then((res) => {
                if (res.status == 200) {
                    let data = res.data.rows;
                    data.forEach((item) => {
                        let obj = {
                            label: item.NAME.val,
                            value: item.ID.val
                        };
                        this.expressList.push(obj);
                    });
                    if(this.expressList.length > 0){
                      if(!this.formInline.COMPANY.value){
                        this.formInline.COMPANY = this.expressList[0]
                      }
                      this.formInline=JSON.parse(JSON.stringify(this.formInline))
                    }
                }
            });
        },
        // 查询签收仓库
        getWarehouseList() {
            let params = { 
                table: 'T_IESWAREHOUSE',
                fixedcolumns: { },
                fkdrplist: {
                    searchcols: ["WAREHOUSENAME"],
                    orderby: [{column: "ID", asc: true}]
                },
                isdroplistsearch: true,
                range: 1000,
                startindex: 0
            };
            network.post('/p/cs/list/query', params).then((res) => {
                if (res.status == 200) {
                    let data = res.data.rows;
                    data.forEach((item) => {
                        let obj = {
                            label: item.WAREHOUSENAME.val,
                            value: item.ID.val
                        };
                        this.warehouseList.push(obj);
                    });
                    if(this.warehouseList.length > 0){
                      if(!this.formInline.STOREID.value){
                        console.log(this.warehouseList[0])
                        this.formInline.STOREID = this.warehouseList[0]
                      }
                      this.formInline=JSON.parse(JSON.stringify(this.formInline))
                    }
                }
            });
        },
        async getReceiveReason(obj) {
          // const { reqType } = obj || {};
          let reqParam = { 
            table: 'T_OMSPACKAGERECEIPT_CAUSE',
            fixedcolumns: { },
            fkdrplist: {
              searchcols: ["ERECEIPT_CAUSE"],
              orderby: [{column: "ID", asc: true}]
            },
            isdroplistsearch: true,
            range: 1000,
            startindex: 0
          };
          const res = await network.post('/p/cs/list/query', reqParam)
          const { status, data = {} } = res || {};
          if (status === 200) {
            const { rows = [] } = data;
            let newOptions = [];
            if (rows.length) {
              newOptions = rows.map(item => {
                return {
                  label: item.ERECEIPT_CAUSE.val,
                  value: item.ID.val
                }
              })
            }
            this.receiveResons = newOptions;
          }
        },
        // 查询品牌
        getBrandList() {
          let params = { 
            table: 'T_IESBRAND',
            fixedcolumns: {},
            fkdrplist: {
              searchcols: ["BRANDNAME"],
              orderby: [{ column: "ID", asc: true }]
            },
            isdroplistsearch: true,
            range: 1000,
            startindex: 0
          };
          network.post('/p/cs/list/query', params).then((res) => {
            if (res.status == 200) {
              let data = res.data.rows;
              data.forEach((item) => {
                let obj = {
                  label: item.BRANDNAME.val,
                  value: item.ID.val
                };
                this.brandList.push(obj);
              });
            }
          });
        },
        selectSkuGoods() {
          if(this.formInline.SKU){
            network.get('/p/cs/query/skuinfo/'+this.formInline.SKU).then((res) => {
              if(res.data.code == 0){
                if(res.data.data){
                  this.playAudio(this.scanOrder);
                  let sameSku = false;
                  let index = 0;
                  if(this.ScanSKUData.length > 0){
                    for(let i=0;i<this.ScanSKUData.length;i++){
                      if(this.ScanSKUData[i].sku == res.data.data.SKU){
                        sameSku = true;
                        index = i;
                        break
                      }
                    }
                  }
                  if(sameSku){
                    this.ScanSKUData[index].num ++
                  }else {
                    let obj = {
                      sku:res.data.data.SKU,
                      num: 1,
                      name:res.data.data.SKUNAME,
                    }
                    this.ScanSKUData.push(obj);
                  }
                  console.log(this.ScanSKUData)
                }else {
                  this.playAudio(this.scanError);
                  this.$Message.error('sku不存在！');
                }
                this.formInline.SKU = '';
              }
            })
          }else {
            this.ScanSign()
          }
        },
        cancel() {
          this.ScanSignCount == 0;
          this.$emit('closeActionDialog', true);
        },
        // 物流单号敲击回车
        submitDISPATCHNO() {
          this.playAudio(this.scanLogistics, '#order-audio');
          if(this.formInline.SCANSKUFLAG == 2){ // 是否扫描SKU为是
            this.$refs.SCANSKU.focus();
          }else { // 是否扫描SKU为否，直接提交
            this.ScanSign()
          }
        },
        ScanSign() {
          if(this.formInline.COMPANY.value == ''){
            return this.$Message.error('物流公司不能为空！');
          }
          if(this.formInline.DISPATCHNO == ''){
            return this.$Message.error('物流单号不能为空！');
          }
          if(this.formInline.STOREID.value == ''){
            return this.$Message.error('签收仓库不能为空！');
          }
          if(this.formInline.SCANSKUFLAG == 2 && this.ScanSKUData.length == 0){
            return this.$Message.error('商品扫描记录不能为空！');
          }
          this.Spinloading = true;
          let params = {
            company: this.formInline.COMPANY.value,
            dispatchno: this.formInline.DISPATCHNO,
            storeid: this.formInline.STOREID.value,
            mobile: this.formInline.MOBILE,
            selladdress: this.formInline.SELLADDRESS,
            brandid: this.formInline.BRAND || '',
            ERECEIPT_CAUSEID: this.formInline.ERECEIPT_CAUSE || "",
            description: this.formInline.DESCRIPTION
          }
          if(this.formInline.SCANSKUFLAG == 2){
            params.items = this.ScanSKUData
          }
          network.post('/p/cs/signpackage/subimt',params).then(res => {
            if(res.data.code == 0){
              this.ScanSignCount ++;
              this.ScanSKUData = [];
              // this.cancel()
              this.formInline.DISPATCHNO = '';
              this.formInline.DESCRIPTION = '';
              this.formInline.MOBILE = '';
              this.formInline.SELLADDRESS = '';
              // 很奇怪这里没生效????
              this.formInline.BRAND = '';
              this.formInline.ERECEIPT_CAUSE = '';
              // console.log(this.formInline, 'this.formInline1')
              this.playAudio(this.success);
              this.Spinloading = false;
              return this.$Message.success('扫描签收成功！');
            }else {
              this.Spinloading = false;
              this.formInline.DISPATCHNO = '';
              this.playAudio(this.scanError);
              this.$Modal.fcError(res.data.message);
              // return this.$Message.error('扫描签收成功！');
            }
          })
        },
        
        // 获取打印音效
        getPrintSound() {
          const params = {
            range: 100,
            startindex: 0,
            table: 'T_OMSSOUNDSET',
            fkdrplist: {
              searchcols: ['TYPE_NAME', 'ID', 'SOUND_ID', 'URL']
            },
            isdroplistsearch: true,
          };
          network.post('/p/cs/list/query', params).then((res) => {
            res.data.rows.forEach(row => {
              if (row.TYPE_NAME.val == '扫描商品') {
                this.scanOrder = row.URL.val;
              } else if (row.TYPE_NAME.val == '失败') {
                this.scanError = row.URL.val;
              } else if (row.TYPE_NAME.val == '成功') {
                this.success = row.URL.val;
              } else if (row.TYPE_NAME.val == '扫描物流') {
                this.scanLogistics = row.URL.val;
              } else if (row.TYPE_NAME.val == '提示') {
                this.scanOk = row.URL.val;
              }
            });
          });
        },

        // 播放语音
        playAudio(url, id = '#audio') {
          const audio = document.querySelector(id);
          audio.src = url;
          audio.play();
        },
      }
    };
  </script>
  
  <style lang='less'>
    .ScanSign .ark-select, .ScanSign .ark-input {
        width: 250px;
    }
    .ScanSign .ark-select-single .ark-select-selection,.ScanSign .ark-input {
      height: 32px;
      margin-top: -4px;
    }
    .ScanSign .ark-select-single .ark-select-selection .ark-select-placeholder,.ScanSign .ark-select-single .ark-select-selection .ark-select-selected-value, .ScanSign .ark-input {
      height: 30px;
      line-height: 30px;
    }
    .ScanSign .ScanSKUTable .ark-input {
      height: 24px;
      line-height: 24px;
      margin-top: 3px;
      width: 100px;
    }
    .ScanSign .ark-form-inline .ark-form-item {
      margin-bottom: 14px;
    }
    .ScanSign .ark-form-item-error-tip {
      padding-top: 0px;
    }
    .ScanSign .partTitle {
      margin-bottom: 10px;
    }
  </style>
  <style scoped lang='less'>
    .ScanSign {
        width: 800px;
    }
    .partTitle {
      display: inline-block;
      width: 100%;
      height:40px;
      line-height: 40px;
      margin-bottom:20px;
      padding-left: 20px;
      background: #f7f8fa;
      font-size: 16px;
      font-weight: 600;
      color: var(--primary-color);

    }
    .countAll {
      font-size: 16px;
      font-weight: 550;
      padding-left: 20px;
      color: var(--primary-color);
    }
    .bottomBtnBox {
      width: calc(100% - 48px);
      margin: 16px auto 0px;
      text-align: center;
      .cancelBtn,.sureBtn {
        width: 72px;
        height: 32px;
        font-size: 12px;
      }
      .sureBtn {
        margin-right: 8px;
      }
      .cancelBtn {
        color: #909399;
        border: 1px solid #DADADA;
      }
    }
  </style>
  