<script>
import {getDevice, getDevices, sf_express_print} from '@/tools/print.tool';
import {getExpressRecordParams} from '@/api/prescription/prescriptionAudit';
import {editPrescriptionCore2, getPrescriptionCore2} from '@/api/prescription/prescriptionCore';
import regionOptions from '@/utils/options';

export default {
  name: 'print_express_75',
  props: {
    id: {type: [String, Number], required: true},
    selectable: Boolean,
  },
  data() {
    const locationValidator = (message) => (rule, value, callback) => {
      if (this.dataset.expressExecutor === '顺丰') {
        if (!value.length || (typeof value === 'string' && !value.trim())) { return callback(new Error(message)); }
      }
      callback();
    };
    return {
      loaded: false,
      preview: true,
      total: 1,

      tag: `print-preview_${Date.now()}`,
      paper: '顺丰快递面单',

      model: null,
      device: null,
      devices: [],
      printing: false,

      submitting: false,
      editable: false,
      expressPayTypeOptions: [],
      expressDechOptions: [],
      regionOptions,
      dataset: {},
      rules: {
        expressExecutor: [{required: true, message: '请选择配送方式'}],
        consignee: [{validator: locationValidator('请输入收件人')}],
        contactNumber: [{validator: locationValidator('请输入收件电话')}],
        // location: [{validator: locationValidator('请选择所属地域')}],
        address: [{validator: locationValidator('请输入详细地址')}],
      },
    };
  },
  computed: {
    loading() {
      return !this.loaded || !this.preview;
    },
    deviceId() {
      return this.device ? this.device.index : '';
    }
  },
  mounted() {
    if (this.selectable) getDevices().then(devices => this.devices = devices);
  },
  methods: {
    async print(preview = false) {
      if (preview) this.loaded = false;
      try {
        const device = await this.getDevice();

        if (preview) {
          this.getDicts('express_dech').then((response) => {this.expressDechOptions = response.data;});
          this.getDicts('express_pay_type').then((response) => {this.expressPayTypeOptions = response.data;});
          const {id, ...model} = await getPrescriptionCore2(this.$props.id);
          this.dataset = {
            id,
            location: model.location,
            consignee: model.consignee,
            contactNumber: model.contactNumber,
            address: model.address,
            expressDech: model.expressDech,
            expressPayType: model.expressPayType,
            expressExecutor: model.expressExecutor,
          };

          if (device == null) await getDevices();
        } else {
          this.printing = true;
          await this.getModel();
          await sf_express_print(this.model, {}, device);
        }
      } catch (e) {}
      this.printing = false;
      this.loaded = true;
    },
    complete() {
      this.$message.success(`开始打印`);
      this.$emit('close', true);
    },

    async getModel() {
      if (this.model) return this.model;
      return getExpressRecordParams({prescriptionCoreId: this.id}).then((res) => {
        this.model = res.data;
        return this.model;
      });
    },

    async getDevice() {
      if (!this.device) this.device = await getDevice(
        `name: Six:${this.paper}`,
        `driver: RP4xx Series 200DPI TSC; paper: ${this.paper}`,
        `paper:${this.paper}`,
        `driver: RP4xx Series 200DPI TSC;`,
      );
      return this.device;
    },

    selected(value) {
      this.device = this.devices.find(device => device.index === value);
    },

    async save() {
      try {
        await this.$refs.form.validate()
        this.submitting = true;
        const {location = [], ...model} = this.dataset;
        [model.province = '', model.city = '', model.region = ''] = location;
        await editPrescriptionCore2(model);
        this.$message.success(`修改成功`);
      } catch (e) {
        if (e === false) this.$message.warning('请补全表单');
      }
      this.submitting = false;
    },
  },
};
</script>

<template>
  <div class="print-preview" v-loading="loading">
    <el-form ref="form" :model="dataset" :rules="rules" label-position="right" label-width="auto" style="margin: 24px 0;" @submit.native.prevent="save()">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="收件人" prop="consignee">
            <el-input v-model="dataset.consignee" placeholder="请输入收件人" :disabled="!editable || submitting"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="收件电话" prop="contactNumber">
            <el-input type="tel" v-model="dataset.contactNumber" placeholder="请输入收件电话" minlength="11"
                      maxlength="11" :disabled="!editable || submitting"/>
          </el-form-item>
        </el-col>
        <el-col :span="24" style="display: flex;">
          <el-form-item label="收件地址" prop="location">
            <el-cascader v-model="dataset.location" :options="regionOptions" :props="{ value: 'label' }"
                         placeholder="请选择省/市/区" clearable :disabled="!editable || submitting"></el-cascader>
          </el-form-item>
          <el-form-item label-width="4px" prop="address" style="flex: auto;">
            <el-input v-model="dataset.address" placeholder="请输入详细地址" :disabled="!editable || submitting"/>
          </el-form-item>
        </el-col>
        <el-col :span="24" style="display: flex;">
          <el-form-item style="flex-basis: 30%;" label="结算方式" prop="expressDech">
            <el-select v-model="dataset.expressDech" placeholder="顺丰标快" clearable
                       :disabled="!editable || submitting">
              <el-option v-for="item in expressDechOptions" :key="item.dictValue"
                         :label="item.dictLabel" :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item style="flex-basis: 30%;" label-width="4px" label="" prop="expressPayType">
            <el-select v-model="dataset.expressPayType" placeholder="月结" clearable
                       :disabled="!editable || submitting">
              <el-option v-for="item in expressPayTypeOptions" :key="item.dictValue"
                         :label="item.dictLabel" :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div style="display: flex; align-items: center; justify-content: space-evenly;">
        <template v-if="editable">
          <el-button style="flex: 1;" :disabled="submitting" @click="editable = false;">取消</el-button>
          <el-button style="flex: 1;" type="primary" :loading="submitting" native-type="submit">保存</el-button>
        </template>
        <template v-else>
          <el-button style="flex: 1;" @click="editable = true;">编辑</el-button>
          <el-select v-if="devices.length" placeholder="打印机" :value="deviceId" @change="selected">
            <el-option v-for="item in devices" :key="item.index" :label="item.name" :value="item.index"></el-option>
          </el-select>
          <el-button style="flex: 3;" type="primary" :loading="printing" @click="printing = true;print()">
            打印
          </el-button>
        </template>
      </div>
    </el-form>
  </div>
</template>

<style scoped lang="scss">
.print-preview {
  margin: auto;
  width: 559px + 100px;
  display: flex;
  flex-direction: column;

  .top {
    height: 40px;
  }

  iframe {
    border: none;
    width: 100%;
    flex: auto;
  }

  > div {
    flex: none;
  }

  .el-select {
    margin: 0 12px;
  }
}
</style>
