<!-- eslint-disable no-irregular-whitespace -->
<template>
  <div
    id="customizedPage-print-vue"
    class="customizedPage-print"
    ref="printConfig"
  >
    <!-- loading -->
    <!-- loading -->
    <Spin
      v-show="isLoading"
      fix
      size="large"
    >
      <div class="loading-wrap">
        <Icon
          type="ios-loading"
          size="24"
          class="demo-spin-icon-load"
        />
        <span class="loading-text" />
      </div>
    </Spin>
    <!-- 内容开始 -->
    <div
      v-for="(item, index) in config"
      :key="index"
      class="customizedPage-print-li"
    >
      <div v-if="item.type == 'select'" class="customizedPage-print-only-select" data-key="CONFIG_1">
        {{ item.title }}:
        <div
          v-if="item.child"
          class="customizedPage-print-select"
        >
          <Select
            :key="item.name"
            v-model="item.value"
            :data-index="item.name"
            :disabled="!enableConfig || item.disabled"
            @on-change="selectChangeOne"
          >
            <Option
              v-for="option in item.child"
              :key="option.name + item.name"
              :value="option.name"
            >
              {{ option.title }}
            </Option>
          </Select>
        </div>
      </div>

      <Checkbox
        v-else
        :value="formData[item.name] ? true : false"
        :disabled="!enableConfig || item.disabled"
        @on-change="CheckboxChange(item.name)"
      >
        <span>{{ item.title }}</span>
      </Checkbox>
      <span
        v-if="item.showTip && enableConfig "
        class="choose"
        @click="chooseOrderTemple(item.showTip)"
      >{{ item.showTip }}</span>
      <span
        v-if="item.showTip && !enableConfig "
        class="choose choose-disabled"
      >{{ item.showTip }}</span>

      <div
        v-if="item.type != 'select' && item.child"
        class="customizedPage-print-select" data-key="CONFIG_2">
        <Select
          :key="item.name"
          v-model="formData[item.name]"
          :data-index="item.name"
          :disabled="!enableConfig || item.disabled"
          @on-change="SelectChange"
        >
          <Option
            v-for="option in item.child"
            :key="option.name + item.name"
            :value="option.name"
          >
            {{ option.title }}
          </Option>
        </Select>
      </div>

      <!-- <ul
        v-if="item.child"
        class="Radio-box"
      >
        <li
          v-for="option in item.child"
          :key="option.name"
          class="Radio"
        >
          <Radio v-model="option.value">
            {{ option.title }}
          </Radio>
        </li>
      </ul> -->
    </div>
    <!-- 选择打印模版 -->

    <!-- 打印前校验信息弹框  -->
    <template v-if="type">
      <!--  -->
      <iframe
        id="print"
        class="printIframe"
        :src="srciframe"
        height="0px"
        width="0px"
      />
      <iframe
        id="printDispatchBill"
        class="printIframe"
        :src="srcIframeDispatchBill"
        width="0px"
        height="0px"
      />
      <!-- 后置出库 -->
      <iframe
        id="postDeliverySrcIframe"
        class="printIframe"
        :src="postDeliverySrcIframe"
        width="0px"
        height="0px"
      />
    </template>
  </div>
</template>

<script>
  const R3 = window.R3;
  const { network } = R3;
  export default {
    data() {
      return {
        config: [],
        isLoading: false,
        goodsType: '1',
        formData: {
          wuliudan: '', // 回显类型（物流单？ value 是选择类型）
          fahuo: '',
          chuku: '',
          clear: false
        },
        srciframe: '', // 物流iframe
        srcIframeDispatchBill: '', // 发货打印地址
        postDeliverySrcIframe: '', // 后置出库的iframe
        CurrentTemplate: '', // 选中的发货单模版
        CallBack: {}, // 回调函数
      };
    },
    props: {
      // 来自哪里，是否需要iframe显示各种html，去加载各个打印组件的js文件
      fromType: {
        type: String,
        default: ''
      },
      type: {
        type: String,
        default: () => ''
      },
      defaultConfig: {
        type: Object,
        default: () => ({})
      },
      enableConfig: {
        type: Boolean,
        default: false
      },
      formConfig: {
        type: Array,
        default: () => [
          {
            title: '自动打印物流单',
            name: 'wuliudan',
            Checkbox: false,
            value: '',
            child: [
              {
                title: '扫描单号后直接打印',
                name: '1',
                value: false,
              },
              {
                title: '所有商品扫描完成后打印',
                name: '2',
                value: false,
              },
              {
                title: '一单一打印',
                name: '3',
                value: false,
              }
            ]

          },
          {
            title: '自动打印发货单',
            name: 'fahuo',
            showTip: '选择发货单',
            showTipSelect: true,
            Checkbox: false,
            value: '',
            child: [
              {
                title: '扫描单号后直接打印',
                name: '1',
                value: false
              },
              {
                title: '所有商品扫描完成后打印',
                name: '2',
                value: false
              },
              {
                title: '一单一打印',
                name: '3',
                value: false
              }
            ]

          },
          {
            title: '自动出库',
            name: 'chuku',
            Checkbox: false,
            value: '',
            child: [
              {
                title: '一单一出库',
                name: '2',
                value: false
              },
              {
                title: '所有商品扫描完成后出库',
                name: '1',
                value: false
              }
            ]

          },
          {
            title: '提交后页面清空',
            name: 'clear',
            Checkbox: false,
            value: false,
          },
        ]
      },
    },
    watch: {
      defaultConfig: {
        handler(val) {
          this.formData = JSON.parse(JSON.stringify(val));
          console.log('🚀 ~ file: printConfig.vue:219 ~ handler ~ this.formData:', this.formData);
        },
        immediate: true
      },
    // formData: {
    //   handler(val) {
    //     console.log(val, '33434,444444');
    //   },
    //   immediate: true
    // }

    },
    created() {
      // 初始化时为window绑定一个方法
      window['chukuExecute'] = (data, autoLoading, fromType) => {
        this.outboundDeliveryOrder(data, autoLoading, fromType);
      }
    },
    methods: {
      print(data) {
        console.log(data)
        console.log('触发公共打印组件内的print')
        let childWindows = this.$refs.printConfig.querySelectorAll('.printIframe');
        console.log("所有的printIframe", childWindows)
        // 向子页面发送 出库的 消息 //contentWindow   出库接口要在获取到物流单号之后调用
        // let chukuFlag = true;
        // for (let i = 0; i < data.chuku.ids.length; i++) {
        //   if (!data.chuku.ids[i].logisticsNumber) {
        //     chukuFlag = false;
        //   }
        // }
        if ((data.wuliu && data.wuliu.ids.length == 0) && data.chuku && data.chuku.ids && JSON.parse(JSON.stringify(data.chuku.ids)).length > 0) {
          let autoLoading = (data.wuliu && data.wuliu.ids.length) || (data.fahuo && data.fahuo.ids.length) || 0;
          console.log('出库啊哈哈哈好', autoLoading, data.chuku);
          this.outboundDeliveryOrder(data.chuku, autoLoading, 'PEND_PRINT');
        }
        let printjiucuo = false;
        if (this.formData.chuku) {
          // 是否走纠错单逻辑
          printjiucuo = true;
        }
        // 通知物流单发货和通知发货单发货
        if (data.wuliu && data.wuliu.callback) {
          this.CallBack.wuliu = data.wuliu.callback;
        }
        if (data.houzhi && data.houzhi.callback) {
          this.CallBack.houzhi = data.houzhi.callback;
        }
        // if (data.houzhi && data.houzhi.callbackerror) {
        //   this.CallBack.houzhiError = data.houzhi.callbackerror;
        // }
        if (data.chuku && data.chuku.callback) {
          this.CallBack.chuku = data.chuku.callback;
        }
        // console.log(789,this.CallBack)
        const logObj = {
          LOG_ID: 3,
          LOG_OPERATOR: `PENNDING_PRINT`,
          LOG_INFO: {
            F_pendData: data,
          },
        }
        this.$comUtils.globalSaveOperateLogFn(logObj);

        childWindows.forEach((item) => {
          item.contentWindow.postMessage({
            type: 'print',
            $_printjiucuo: printjiucuo,
            data: {
              wuliu: {
                ids: (data.wuliu && data.wuliu.ids) || []
              },
              chuku: {
                ids: (data.chuku && data.chuku.ids) || []
              },
              fahuo: data.fahuo,
              houzhi: {
                data: data.houzhi ? data.houzhi.data : '',
                isPrintDelivery: data.houzhi ? data.houzhi.isPrintDelivery : '', // 是否打印出库单
                isDeliveryAfterPrint: data.houzhi ? data.houzhi.isDeliveryAfterPrint : '' // 是否自动出库
              } // 后置出库
            },

          }, '*');
        });
      },

      SelectChange() {
        // 选择配置
        this.$emit('on-print-change', this.formData);
      },
      selectChangeOne() {
        this.$emit('onPrintChangeOne', this.goodsType);
      },
      CheckboxChange(name) {
        // 用于勾选和下拉的组件
        if (typeof this.formData[name] === 'string' && this.formData[name] && name !== 'clear') {
          this.formData[name] = '';
        }

        // 仅勾选组件
        if (typeof this.formData[name] === 'boolean') {
          this.formData[name] = !this.formData[name];
        }

        this.$emit('on-print-change', this.formData);
      },
      getShippingTemplate() {
        // 查看浏览器是否有缓存的发货单模版
        let { customizedModuleId, customizedModuleName } = this.$route.params;
        let shippingTemplate = localStorage.getItem(`${customizedModuleName}_${customizedModuleId}_shippingTemplate`);
        if (shippingTemplate) {
          return JSON.parse(shippingTemplate);
        }
        return '';
      },
      async getOrderTemple() {
        //  获取发货单模版
        this.isLoading = true;
        let params = {
          table: 'T_OMSPRINTTEMPLATE', startindex: 0, range: 1000, fixedcolumns: { TemplateType: ['3'] }
        };
        let resData = await network.post('/p/cs/list/query', params);
        return resData;
      },
      async chooseOrderTemple(title) {
        let resData = await this.getOrderTemple();
        this.isLoading = false;
        if (!resData.data.rows || (resData.data.rows && resData.data.rows.length < 1)) {
          window.Ark.Modal.fcError({
            title: '提示',
            width: 300,
            mask: true,
            showCancel: false,
            content: '请去打印模版配置配置出库单模版',
          });
          return true;
        }
        this.CurrentTemplate = this.getShippingTemplate();
        let PrintOutTemp = resData.data.rows.reduce((arr, item)=>{
          Object.keys(item).forEach((option)=> {
            if (item[option].refobjval) {
              item[option] = item[option].refobjval;
            } else {
              item[option] = item[option].val;
            }
          });
          arr.push(item);
          return arr;
        }, []);
        let self = this;
        window.Ark.Modal.fcError({
          title: '请选择发货单模版',
          width: 300,
          mask: true,
          className: 'orderPutTemp',
          showCancel: true,
          contentTemplate: {
            data() {
              return {
                PrintOutTemp,
                value: self.CurrentTemplate.ID
              };
            },
            template:
              `<div>
                      <Select class="orderPutTempSelect" @on-change="change" style="width:220px" :value="value">
                        <Option v-for="item in PrintOutTemp" :value="item.ID" :key="item.ID">{{ item.TEMPLATENAME}}</Option>
                   </Select>
                  </div>`,
            methods: {
              change(value, item) {
                const selectItemIndex = PrintOutTemp.findIndex(item => item.ID === value)
                if(selectItemIndex > -1) {
                  self.CurrentTemplate = PrintOutTemp[selectItemIndex]
                }
              }
            }
          },
          onOk: ()=>{
            let { customizedModuleId, customizedModuleName } = this.$route.params;
            localStorage.setItem(`${customizedModuleName}_${customizedModuleId}_shippingTemplate`, JSON.stringify(self.CurrentTemplate));
          }
        });
      },
      ship(type, res) {
        if(type == 'houzhierror'){
          this.$parent.$parent.$parent.$parent.$children.find(item => item.instanceRoute === '/CUSTOMIZED/POSTDELIVERY/3323').showGoodErrorTip()
        }else {
          // 出库回调
          this.CallBack[type](res);
        }
      },
      async outboundDeliveryOrder(reqData, autoLoading, fromType) {
            // 关闭loading

        try {
          let logType = 'NORMAL';// 日志标记类型
            // 关闭loading
          if (document.querySelector('#second-pick-loading')) {
            document.querySelector('#second-pick-loading').style.display = 'none';
          }
            // 出库单出库接口
          const res = await network.post('/p/cs/order/ship/muti', reqData.ids);
          const resultData = res.data || {};
          const { code, message, data } = resultData || {};
          if (code === 0) {
            logType = 'SUCCESS';
            // 回到二次扫描界面继续调用接口更新界面状态
            const { errors } = data || {};
            const backError = errors || [];
            this.CallBack.chuku(backError, reqData.ids);
          } else {
            logType = 'ERROR';
            window.Ark.Message.error({
              content: message,
              origin: autoLoading > 0 ? 'ship' : false,
              duration: 2,
            });
          }
          // 日志记录
          const logObj = {
            LOG_ID: 6,
            LOG_OPERATOR: `MUTI_${logType}_${fromType}`,
            LOG_INFO: {
              F_mutiReqData: reqData,
              F_mutiResData: data,
            },
          }
          this.$comUtils.globalSaveOperateLogFn(logObj);
        } catch (error) {
          this.$Modal.error({
            title: '注意',
            showCancel: false,
            content: '当前单据出库异常，请及时联系管理人员!!',
            onOk: () => {
              this.$emit('on-common-handle', { handleType: 'MUTI_ERROR' })
            },
          });
        }
       
      }
    },
    mounted() {
      this.config = this.formConfig;
      this.formData = this.defaultConfig;
      setTimeout(() => {
        // 扫描入口时不需要各个打印组件
        if (this.fromType !== 'NEW_SCAN_IN') {
          this.srciframe = '/iframe/PrintVue/wuliudan.html';
          this.srcIframeDispatchBill = '/iframe/PrintVue/fahuodan.html';
          this.postDeliverySrcIframe = '/iframe/PrintVue/PostDelivery.html';
        }
      }, 50);
      this.$el._vue_ = this;
    }
  };
</script>

<style lang="less" scoped>
.customizedPage-print {
  padding: 17px 22px;
  color: #333333;

  .customizedPage-print-only-select {
    display: flex;
    align-items: center;
    .customizedPage-print-select {
      width: 100%;
      margin: 20px 10px;
    }
  }

  .customizedPage-print-select {
    margin: 6px 20px 20px;
  }

  .customizedPage-print-li {
    ul {
      padding: 6px 20px;

      li {
        padding-bottom: 6px;
      }
    }

  }

  .choose {
    cursor: pointer;
    color: var(--primary-color);

  }
  .choose-disabled{
      color: #999;
  }
}

</style>
<style lang="less">
.orderPutTempSelect {
  i {
    font-size: 14px!important;
  }
}
</style>
