<template>
  <div
    id="element-main"
    class="EditShippingWarehouse"
  >
    <div
      v-if="showMessage"
      v-html="message"
    />
    <div
      v-else-if="showConfirmMessage"
      v-html="confirmMessage"
    />
    <Form
      v-else
      ref="formModel"
      :model="formModel"
      :rules="formRule"
      :label-width="140"
      label-position="right"
    >
      <FormItem
        label="请选择发货仓库"
        prop="shippingWarehouse"
      >
        <Select
          v-model="formModel.shippingWarehouse"
          filterable
        >
          <!-- <Option
            v-for="item in shippingWarehouses"
            :key="item.ID.val"
            :value="item.ID.val"
          >
            {{ item.WAREHOUSENAME.val }}
          </Option> -->
          <Option
            v-for="item in shippingWarehouses"
            :key="item.id"
            :value="item.id"
          >
            {{ item.name }}
          </Option>
        </Select>
      </FormItem>
      <div class="appointBox" style="display: flex;align-items: center;">
        <Tooltip
            placement="right"
            transfer
            max-width="230"
            content="勾选后，订单将锁定当前发货仓，缺货重新分仓时会排除此类订单保留当前发货仓进行缺货重新占单。后续可以通过修改发货仓或者参数不勾选重置选中订单进行解锁"
          >
          <Icon
            style="color: var(--primary-color);margin-right: -18px;margin-left: -10px;"
            type="md-information-circle"
          />
        </Tooltip>
        <FormItem
          label="是否指定当前订单仓库"
          class="appoinwarehouse"
        >
        <Checkbox v-model="formModel.designated_warehouse"></Checkbox>
        </FormItem>
      </div>
    </Form>
    <businessButton :btn-config="btnConfig" />
  </div>
</template>

<script lang="js">
  import businessButton from 'professionalComponents/businessButton';
  import common from '@yunque/service/modules/common';
  import { showModalFcError } from '@yunque/service/modules/utils';

  const R3 = window.R3;
  const { network, urlSearchParams, store } = R3;

  export default {
    name: 'ModifyShippingWarehouse',
    components: {
      businessButton
    },
    async created() {
      // this.$emit('setTitle', '批量分配发货仓库');

      // 父组件传过来的 selectRowData 有一些字段不是表中原来的值，所以需要重新查询
      // for (let i = 0; i < this.idArray.length; i++) {
      //   const id = this.idArray[i];
      //   const row = await common.objectQuery({
      //     objid: id,
      //     table: this.$route.params.tableName
      //   });
      //   this.selectRows.push(row);
      // }
      const row = await common.getOrderList({
        ids: this.idArray,
      });
      this.selectRows = row.data.data;

      // 判断是否天猫时效订单
      let istmallPromise = this.selectRows.some(a => a.TIMING_PROMISE != null && a.TIMING_PROMISE.toUpperCase() == 'TMALLPROMISE');
      // 未审核的3pl订单可以修改仓库
      let threeplArr = this.selectRows.filter(a => a.THREEPLTIMING == 1 && a.ORDERSTATUS >= 3);

      if (threeplArr.length > 0) {
        this.message = `订单编号为 ${threeplArr.join(',')} 的订单是3PL订单，已审核状态后不支持更换发货仓库`;
        return;
      }

      if (istmallPromise) {
        this.confirmMessage = '选中单据为天猫时效订单，更换发货仓库可能会影响时效，造成赔付，确认修改？';
      }

      // const param = {
      //   table: 'T_IESWAREHOUSE',
      //   range: 5000,
      //   isdroplistsearch: true,
      //   fkdrplist: {
      //     searchcols: ['ID', 'WAREHOUSENAME'],
      //     orderby: [{
      //       column: 'WAREHOUSENAME',
      //       asc: true
      //     }]
      //   }
      // };
      // const getShippingWarehousesRsp = await common.listQuery(param);
      const params = {
        ids: this.idArray
      };
      network.post('/p/cs/qm/batchQueryStoreByShopId', params).then(res => {
        if (res.data.code == 0) {
          let ieswarehouse = [];
          res.data.data.ieswarehouse.forEach(item => {
            let obj = {
              name: item.name,
              id: String(item.id)
            };
            ieswarehouse.push(obj);
          })
          this.shippingWarehouses = ieswarehouse;
        }
      });
      // this.shippingWarehouses = getShippingWarehousesRsp.rows;
    },
    props: {
      idArray: { // 获取ID用于多选
        type: Array,
        default: () => []
      },
      itemId: {// 获取当前子表表名
        type: String,
        default: () => ''
      }
    },
    data() {
      return {
        message: '',
        confirmMessage: '',
        shippingWarehouses: [],
        selectRows: [], // 选择的行数据
        formModel: {
          shippingWarehouse: '',
          designated_warehouse: ''
        },
        formRule: {
          shippingWarehouse: [
            { required: true, message: '请选择发货仓库', trigger: 'blur' }
          ]
        },
        btnConfig: {
          typeAll: 'error', // 按钮统一风格样式
          btnsite: 'right', // 按钮位置 (right , center , left)
          buttons: [
            {
              type: '', // 按钮类型
              text: '取消', // 取消 按钮文本
              icon: '', // 按钮图标
              size: '', // 按钮大小
              disabled: false, // 按钮禁用控制
              btnclick: () => {
                this.$emit('closeActionDialog', false);
              } // 按钮点击事件
            },
            {
              type: '', // 按钮类型
              text: '确定', // 按钮文本
              icon: '', // 按钮图标
              size: '', // 按钮大小
              disabled: false, // 按钮禁用控制
              btnclick: () => {
                this.submit();
              }, // 按钮点击事件
            }
          ]
        }
      };
    },
    computed: {
      /**
       * 显示提示信息
       * @returns {boolean}
       */
      showMessage() {
        if (this.message) {
          let btnCancel = this.btnConfig.buttons[0];
          btnCancel.text = '确定';
          this.btnConfig.buttons = [btnCancel];

          return true;
        }
        return false;
      },
      /**
       * 显示 confirm 确认信息
       * @returns {boolean}
       */
      showConfirmMessage() {
        return this.confirmMessage ? true : false;
      }
    },
    methods: {
      submit() {
        console.log(this.formModel)
        if (this.showConfirmMessage) {
          this.confirmMessage = '';
          return;
        }

        this.$refs.formModel.validate(async (valid) => {
          console.log(valid)
          if (!valid) {
            return;
          }

          try {
            let warehouseIds = this.idArray.map(p => ({
              ORDERID: p,
              IESSTOREID: this.formModel.shippingWarehouse,
              DESIGNATED_WAREHOUSE: this.formModel.designated_warehouse?1:0
            }));
            const param = {
              ids: this.idArray,
              param: {
                T_OMSONLINEORDER: warehouseIds,
              },
              tableName: this.$route.params.tableName,
              actionName: 'T_V_OMSONLINEORDER_修改发货仓_SP',
              isContainsParam: true
            };
            const rsp = await common.ChangeWarehouse(param);
            if (rsp === null) {
              return;
            }

            if(rsp.code === 10) {
              const msgObj = JSON.parse(rsp.message)
              const errorList = msgObj.list.find((item) => item.code === 10)
              this.$Modal.fcWarning({
                title: '提示',
                mask: true,
                content: `${msgObj.msg}</br>订单[${errorList.orderids.join(',')}]${errorList.msg}`,
                showCancel: true,
                onOk: () => {
                  // this.modifyStore();
                }
              });
            } else if (rsp.code !== 0) {
              this.$Modal.error({
                title: '友情提示',
                content: rsp.message
              });
            } else {
              this.$emit('closeActionDialog', true);
              this.$Message.success(rsp.message);
            }
          } catch (e) {
            console.error(e);
            showModalFcError('错误', `系统出现异常，请联系管理员（${e}）`);
          }
        });
      },

      // 确认修改仓库
      async modifyStore() {
        try {
          let warehouseIds = this.idArray.map(p => ({
            ORDERID: p,
            IESSTOREID: this.formModel.shippingWarehouse,
            DESIGNATED_WAREHOUSE: this.formModel.designated_warehouse?1:0
          }));
          const param = {
            ids: this.idArray,
            param: {
              T_OMSONLINEORDER: warehouseIds,
            },
            tableName: this.$route.params.tableName,
            actionName: 'sp_oms_againassignwarehouse',
            isContainsParam: true
          };
          const rsp = await common.exeAction(param);
          if (rsp === null) {
            return;
          }

          if (rsp.code !== 0) {
            this.$Modal.error({
              title: '友情提示',
              content: rsp.message
            });
          } else {
            this.$emit('closeActionDialog', true);
            this.$Message.success('撤回并改仓成功');
          }
        } catch (e) {
          console.error(e);
          showModalFcError('错误', `系统出现异常，请联系管理员（${e}）`);
        }
      }
    }
  };
</script>
<style lang = 'less'>
.EditShippingWarehouse .ark-select-single .ark-select-selection {
  height: 32px;
}
.appoinwarehouse.ark-form-item {
  margin-bottom: 0;
}

</style>
<style scoped>
  #element-main {
    width: 450px;
    padding: 0 15px;
  }
</style>
