<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container>
      <w-form ref="form" slot="detail" :model="model" :rules="validatorRules" v-next>
        <w-row>
          <w-col :span="12">
            <w-form-item label="需求单状态" prop="status">
              <j-dict-select-tag v-model="model.status" placeholder="" disabled dict-code="DemanStatus" />
            </w-form-item>
          </w-col>
          <w-col :span="12">
            <w-form-item label="需求单号" prop="reqsNo">
              <w-input v-model="model.reqsNo" maxlength="10" disabled />
            </w-form-item>
          </w-col>
          <w-col :span="12">
            <w-form-item label="需求单类型" prop="reqsType">
              <j-dict-select-tag
                v-model="model.reqsType"
                type="radio"
                :disabled="model.id && model.id !== ''"
                placeholder="请选择需求单类型"
                dict-code="DemanType"
              />
            </w-form-item>
          </w-col>
          <w-col :span="12">
            <w-form-item label="需求人" prop="requesterId">
              <AppprovalUserSelect
                v-model="model.requesterId"
                v-required-color="true"
                :key="componentKey"
                placeholder="请选择需求人"
                :disabled="formDisabled"
                @change="
                  (data) => {
                    data && data.length > 0
                      ? $set(model, 'requesterName', data[0].userName)
                      : $set(model, 'requesterName', '');
                  }
                "
              />
            </w-form-item>
          </w-col>
          <w-col :span="12">
            <w-form-item label="预计发运/到货日期" prop="sendArrivalTime">
              <w-date v-model="model.sendArrivalTime" :disabled="formDisabled" placeholder="请选择预计发运/到货日期" />
            </w-form-item>
          </w-col>

          <w-col :span="12">
            <w-form-item label="事业部" prop="bussDepartCode">
              <j-dict-select-tag
                v-model="model.bussDepartCode"
                :popperAppendToBody="true"
                v-required-color="true"
                placeholder="请选择事业部"
                dict-code="BU"
                v-if="!formDisabled"
              />
              <w-input v-else disabled v-model="model.bussDepartCode_dictText" />
            </w-form-item>
          </w-col>

          <w-col :span="12">
            <w-form-item label="进口企业" prop="impEnterpCode">
              <j-search-select-tag
                v-if="!formDisabled"
                v-model="model.impEnterpCode"
                :dict-options="LegalPersonOptions"
                popperAppendToBody
                :format="'splicing'"
                placeholder="请选择进口企业"
                @getselectedObj="
                  (obj) => {
                    model.impEnterpName = obj && obj.text;
                    model.impCtryCode = obj && obj.record.country;
                    model.impCtryName = obj && obj.record.countryName;
                    impIsMideaMerger = obj && obj.record.isMideaMerger;
                  }
                "
              />
              <w-input v-else disabled :value="joinWithDash(model.impEnterpCode, model.impEnterpName)" />
            </w-form-item>
          </w-col>

          <w-col :span="12">
            <w-form-item label="进口国" prop="impCtryCode">
              <w-input disabled :value="joinWithDash(model.impCtryCode, model.impCtryName)" />
            </w-form-item>
          </w-col>

          <w-col :span="12">
            <w-form-item label="出口企业" prop="expEnterpCode">
              <j-search-select-tag
                v-if="!formDisabled"
                v-model="model.expEnterpCode"
                :dict-options="LegalPersonOptions"
                :format="'splicing'"
                popperAppendToBody
                placeholder="请选择出口企业"
                @getselectedObj="
                  (obj) => {
                    model.expEnterpName = obj && obj.text;
                    model.expCtryCode = obj && obj.record.country;
                    model.expCtryName = obj && obj.record.countryName;
                    expIsMideaMerger = obj && obj.record.isMideaMerger;
                  }
                "
              />
              <w-input v-else disabled :value="joinWithDash(model.expEnterpCode, model.expEnterpName)" />
            </w-form-item>
          </w-col>

          <w-col :span="12">
            <w-form-item label="出口国" prop="expCtryCode">
              <w-input disabled :value="joinWithDash(model.expCtryCode, model.expCtryName)" />
            </w-form-item>
          </w-col>

          <w-col :span="12">
            <w-form-item label="备注" prop="demo">
              <w-input v-model="model.demo" maxlength="50" :disabled="formDisabled" placeholder="请输入备注" />
            </w-form-item>
          </w-col>
        </w-row>
      </w-form>
    </j-form-container>
  </a-spin>
</template>

<script>
import { getAction, httpAction } from '@/api/manage';
import AppprovalUserSelect from '@/components/AppprovalUserSelect/index';
import { mapGetters } from 'vuex';
export default {
  name: 'MergerReqsModalForm',
  components: {
    AppprovalUserSelect,
  },
  props: {
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    return {
      model: {
        reqsType: '1',
        impCtryCode: '',
        impCtryName: '',
        expCtryName: '',
        expCtryCode: '',
      },
      confirmLoading: false,
      validatorRules: {
        reqsType: [{ required: true, message: '请选择需求单类型!', trigger: 'blur' }],
        requesterId: [{ required: true, message: '请选择需求人!' }],
        bussDepartCode: [{ required: true, message: '请选择事业部!' }],
        impEnterpCode: [{ required: true, message: '请选择进口企业!' }],
        expEnterpCode: [{ required: true, message: '请选择出口企业!' }],
      },
      url: {
        add: '/merger/mergerReqsHead/add',
        edit: '/merger/mergerReqsHead/edit',
        queryById: '/merger/mergerReqsHead/queryById',
        legalPersonList: '/merger/mergerLegalPersonOrg/list',
        bodyList: '/merger/mergerReqsList/list',
      },
      LegalPersonOptions: [],
      componentKey: 0,
      expIsMideaMerger: '',
      impIsMideaMerger: '',
    };
  },
  computed: {
    formDisabled() {
      return this.disabled;
    },
  },
  watch: {
    'model.impEnterpCode'(newVal) {
      if (!newVal) {
        this.$set(this.model, 'impEnterpName', '');
        this.$set(this.model, 'impCtryCode', '');
        this.$set(this.model, 'impCtryName', '');
      }
    },
    'model.expEnterpCode'(newVal) {
      if (!newVal) {
        this.$set(this.model, 'expCtryName', '');
        this.$set(this.model, 'expCtryCode', '');
        this.$set(this.model, 'expEnterpName', '');
      }
    },
  },
  created() {
    // 备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
  },
  methods: {
    ...mapGetters(['userInfo']),
    add() {
      this.componentKey += 1;
      this.visible = true;
      this.model = Object.assign({}, this.modelDefault);
      this.$refs.form.resetFields();
      this.$set(this.model, 'requesterId', this.userInfo().username);
      this.getLegalPersonOption();
    },
    edit(record) {
      this.model = Object.assign({}, record);
      this.visible = true;
      this.getLegalPersonOption();
    },
    getLegalPersonOption() {
      getAction(this.url.legalPersonList, { pageNo: 1, pageSize: 999 })
        .then((res) => {
          if (res.success) {
            this.LegalPersonOptions = res.result.records.map((record) => ({
              value: record.businessNo,
              text: record.businessName,
              record: record,
            }));
          } else {
            this.$message.warning(res.message);
          }
        })
        .finally(() => {});
    },
    submitForm() {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.expIsMideaMerger === '0' && this.impIsMideaMerger === '0') {
            this.$message.warning('进口企业和出口企业的归类标志均不需要归类，请确认！');
            return;
          }
          that.confirmLoading = true;
          const httpurl = this.model.id ? this.url.edit : this.url.add;
          const method = this.model.id ? 'put' : 'post';
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success('保存成功');
                that.model = res.result || that.model;
                that.$emit('getHeadId');
                // that.$emit('close')
              } else {
                that.$message.warning(res.message);
              }
            })
            .finally(() => {
              that.confirmLoading = false;
            });
        }
      });
    },
    joinWithDash(code, name) {
      // 判断code是否存在（非null、非undefined、非空字符串）
      const isCodeValid = code !== null && code !== undefined && code !== '';

      // 如果code不存在，直接返回空
      if (!isCodeValid) {
        return '';
      }

      // code存在时，处理name（空值则显示空字符串）
      const nameStr = name === null || name === undefined ? '' : name;

      // 返回拼接结果
      return `${code}-${nameStr}`;
    },
  },
};
</script>
