<template>
  <a-modal
    centered
    class="offlineImport-modal"
    :footer="null"
    :maskClosable="false"
    title="导入"
    v-model="isShow"
    @cancel="isShow=false"
    width="60%">
    <div class="offlineImport-con">
      <!-- 可导入数据 -->
      <p style="font-weight:bold;">可导入数据{{ loadData.length }}条，确认要批量下线吗？</p>
      <a-form-model :model="form" ref="ruleForm" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="下线选项" prop="offlineReasonType">
          <v-select
            code="OFFLINE_REASON_TYPE"
            id="offlineImport-offlineReasonType"
            v-model="form.offlineReasonType"
            allowClear
            placeholder="请选择下线选项"
          ></v-select>
        </a-form-model-item>
        <a-form-model-item label="通用编码" :required="form.offlineReasonType=='通用'">
          <a-table
            class="sTable"
            ref="table"
            size="small"
            :rowKey="(record) => record.allocateSn"
            :columns="nowColumns"
            :dataSource="loadData"
            :loading="loading"
            :scroll="{ y: 200}"
            :pagination="false"
            bordered>
            <template slot="currency" slot-scope="text, record">
              <productCodeList :ref="'productCodeList'+record.no" :dealerVal="record.commonName" @change="e => productCodeChange(e, record)" />
            </template>
          </a-table>
        </a-form-model-item>
        <a-form-model-item label="下线备注">
          <a-textarea
            id="offlineImport-offlineRemark"
            v-model="form.offlineRemark"
            placeholder="请输入下线备注(最多60个字符)"
            :maxLength="60"
            :auto-size="{ minRows: 2, maxRows: 5 }"
            allowClear
          />
        </a-form-model-item>
      </a-form-model>

      <a-divider />
      <!-- 不可导入数据 -->
      <p class="red">不可导入数据{{ unLoadData.length }}条</p>
      <a-table
        class="sTable"
        ref="unTable"
        size="small"
        :rowKey="(record) => record.errorDesc"
        :columns="nowUnColumns"
        :dataSource="unLoadData"
        :loading="loading"
        :scroll="{ y: 200}"
        :pagination="false"
        bordered>
      </a-table>
      <!-- 按钮 -->
      <div class="btn-con">
        <a-button
          type="primary"
          id="offlineImport-submit"
          size="large"
          :class="loadData.length==0?'button-grey':'button-primary'"
          @click="handleSubmit"
          style="padding: 0 40px;">确认导入</a-button>
        <a-button
          id="offlineImport-cancel"
          size="large"
          class="button-cancel"
          @click="isShow=false"
          style="padding: 0 40px;margin-left: 15px;">取消</a-button>
        <a-button
          type="primary"
          id="offlineImport-error"
          size="large"
          class="button-error"
          @click="handleError"
          style="padding: 0 40px;margin-left: 15px;">导出错误项</a-button>
      </div>
    </div>
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { hdExportExcel } from '@/libs/exportExcel'
// 组件
import { VSelect } from '@/components'
import productCodeList from '@/views/common/productCodeList.vue'
// 接口
import { offlineImport, exportErrorOffline } from '@/api/product'
export default {
  name: 'SalesofflineImportModal',
  mixins: [commonMixin],
  components: { VSelect, productCodeList },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    paramsData: {// 导入数据
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data () {
    return {
      labelCol: { span: 2 },
      wrapperCol: { span: 22 },
      isShow: this.openModal, //  是否打开弹框
      form: {
        type: 'offline', // 下线状态
        offlineReasonType: undefined, // 通用编码类型
        offlineRemark: '', // 下线备注
        offlineProductList: []// 下线产品列表
      },
      nowColumns: [
        { title: '序号', dataIndex: 'no', width: '3%', align: 'center' },
        { title: '产品编码', dataIndex: 'code', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '通用编码', scopedSlots: { customRender: 'currency' }, width: '5%', align: 'center' }
      ],
      loadData: [], // 可导入数据
      nowUnColumns: [
        { title: '序号', dataIndex: 'no', width: '3%', align: 'center' },
        { title: '产品编码', dataIndex: 'code', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '通用编码', dataIndex: 'commonCode', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '备注', dataIndex: 'remark', width: '5%', align: 'center', customRender: function (text) { return text || '--' } }
      ],
      unLoadData: [], // 导入错误数据
      loading: false, // 列表加载状态
      // 选择下线产品 规则验证
      rules: {
        offlineReasonType: [
          { required: true, message: '请选择下线选项', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    // 产品编码 change
    productCodeChange (val, row) {
      row.commonSn = val.key
      if (val && val.row) {
        row.commonCode = val.row.code
      }
    },
    // 获取导入数据
    getData () {
      const _this = this
      this.loading = true
      const params = {
        path: this.paramsData.path
      }
      offlineImport(params).then(res => {
        _this.loading = false
        if (res.status == 200) {
          if (res.data.rightList && res.data.rightList.length > 0) {
            res.data.rightList.map((item, index) => {
              item.no = index + 1
              _this.$nextTick(() => {
                const val = 'productCodeList' + item.no
                _this.$refs[val].setData({ key: item.commonCode })
              })
            })
          }
          if (res.data.errorList && res.data.errorList.length > 0) {
            res.data.errorList.map((item, index) => {
              item.no = index + 1
            })
          }
          _this.loadData = res.data.rightList || []
          _this.unLoadData = res.data.errorList || []
        }
      })
    },
    // 确认导入
    handleSubmit () {
      if (this.loadData.length == 0) {
        this.$message.warning('无可导入产品！')
      } else {
        const _this = this
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            // 通用必填时判断
            _this.isHandleOk()
          } else {
            return false
          }
        })
      }
    },
    // 验证是否是通用编码
    isHandleOk () {
      const _this = this
      if (_this.form.offlineReasonType === '通用') {
        const flag = _this.loadData.some(item => !item.commonSn)
        if (flag) {
          _this.$message.warning('通用编码不能为空！')
          return
        }
      }
      _this.$set(_this.form, 'offlineProductList', _this.loadData)
      _this.$emit('ok', JSON.parse(JSON.stringify(_this.form)))
      _this.isShow = false
    },
    // 导出错误项
    handleError () {
      const _this = this
      if (_this.unLoadData.length < 1) {
        _this.$message.info('暂无可导出的错误项~')
        return
      }
      _this.spinning = true
      hdExportExcel(exportErrorOffline, _this.unLoadData, '导出产品错误项', function () {
        _this.spinning = false
      })
    },
    // 重置表单选择
    resetSearchForm () {
      this.loadData = []
      this.unLoadData = []
      this.form = {
        type: 'offline',
        offlineReasonType: undefined,
        offlineRemark: '',
        offlineProductList: []
      }
      this.$refs.ruleForm.resetFields()
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.resetSearchForm()
      } else {
        this.getData()
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .offlineImport-modal{
    .offlineImport-con{
      .red{
        color: #f30;
      }
      .btn-con{
        text-align: center;
        margin: 30px 0 20px;
        .button-cancel,.button-error{
          font-size: 12px;
        }
      }
    }
  }
</style>
