<!-- 编辑弹窗 -->
<template>
  <ele-modal
    width="75%"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑配件' : '添加配件'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <div style="background-color: #f3f3f3; padding: 8px">
      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        :label-col="{ md: { span: 7 }, sm: { span: 4 }, xs: { span: 24 } }"
        :wrapper-col="{ md: { span: 17 }, sm: { span: 20 }, xs: { span: 24 } }"
      >
        <a-card title="基本信息" :bordered="false">
          <a-row :gutter="16">
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="配件分类" name="accessoryCategory">
                <AccessoryCategory
                  v-model:value="form.accessoryCategory"
                  valueField="label"
                  placeholder="请选择配件分类"
                  class="ele-fluid"
                />
              </a-form-item>
              <a-form-item label="配件规格" name="accessorySpecs">
                <a-input
                  allow-clear
                  placeholder="请输入配件规格"
                  v-model:value="form.accessorySpecs"
                />
              </a-form-item>
              <a-form-item label="重量" name="accessoryWeight">
                <a-input
                  allow-clear
                  placeholder="请输入配件规格"
                  v-model:value="form.accessoryWeight"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="配件名称" name="accessoryName">
                <a-input
                  allow-clear
                  placeholder="请输入配件名称"
                  v-model:value="form.accessoryName"
                />
              </a-form-item>
              <a-form-item label="单位" name="accessoryUnit">
                <a-input
                  allow-clear
                  placeholder="请输入配件单位"
                  v-model:value="form.accessoryUnit"
                />
              </a-form-item>
              <a-form-item label="单价" name="accessoryPrice">
                <a-input-number
                  allow-clear
                  :min="0"
                  :precision="2"
                  style="width: 200px"
                  placeholder="请输入配件单价"
                  v-model:value="form.accessoryPrice"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="设备型号" name="accessoryModel">
                <TowerSelectModel
                  :placeholder="`请选择设备型号`"
                  v-model:value="form.accessoryModel"
                  @done="chooseAccessoryModel"
                />
              </a-form-item>
              <a-form-item label="使用年限" name="lifeYear">
                <a-input
                  allow-clear
                  placeholder="请输入使用年限"
                  v-model:value="form.lifeYear"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        <a-divider style="height: 8px" />
        <a-card title="出厂信息" :bordered="false">
          <a-row :gutter="16">
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="配件编号" name="accessoryNo">
                <a-input
                  allow-clear
                  placeholder="请输入当前位置"
                  v-model:value="form.accessoryNo"
                />
              </a-form-item>
              <a-form-item label="产权单位" name="companyName">
                <TowerCompany
                  :placeholder="`请选择租赁单位`"
                  v-model:value="form.companyName"
                  :customer-type="`产权单位`"
                  @done="chooseCompanyName"
                />
              </a-form-item>
              <a-form-item label="备注" name="comments">
                <a-textarea
                  :rows="4"
                  :maxlength="200"
                  placeholder="请输入备注"
                  v-model:value="form.comments"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="制造厂商" name="manufactor">
                <a-input
                  allow-clear
                  placeholder="请输入制造厂商"
                  v-model:value="form.manufactor"
                />
              </a-form-item>
              <a-form-item label="厂商编号" name="manufactorNo">
                <a-input
                  allow-clear
                  placeholder="请输入厂商编号"
                  v-model:value="form.manufactorNo"
                />
              </a-form-item>
            </a-col>
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="出厂日期" name="factoryDate">
                <a-date-picker
                  class="ele-fluid"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择日期"
                  v-model:value="form.factoryDate"
                />
              </a-form-item>
              <a-form-item label="报废日期" name="scrapDate">
                <a-date-picker
                  class="ele-fluid"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择日期"
                  v-model:value="form.scrapDate"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        <a-divider style="height: 8px" />
        <a-card title="多选适配设备型号" :bordered="false">
          <a-row :gutter="16">
            <a-col
              v-bind="styleResponsive ? { md: 8, sm: 24, xs: 24 } : { span: 8 }"
            >
              <a-form-item label="设备型号" name="accessoryModelMultiple">
                <TowerSelectModelMultiple
                  :placeholder="`请选择设备型号`"
                  v-model:value="form.accessoryModelMultiple"
                  @done="chooseMultiple"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
      </a-form>
    </div>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject } from 'ele-admin-pro';
  import { addAccessory, updateAccessory } from '@/api/tower/accessory';
  import { Accessory } from '@/api/tower/accessory/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { Customer } from '@/api/oa/customer/model';
  import { Category } from '@/api/goods/category/model';
  import { TowerModel } from '@/api/tower/model/model';

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Accessory | null;
    categoryList?: Category[];
    modelTree?: TowerModel[];
    modelList?: TowerModel[];
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  // 表格选中数据
  const formRef = ref<FormInstance | null>(null);

  // 用户信息
  const form = reactive<Accessory>({
    accessoryId: undefined,
    accessoryName: '',
    accessoryNo: '',
    accessoryCategory: undefined,
    accessoryModel: '',
    accessoryModelMultiple: [],
    accessorySpecs: '',
    accessoryPrice: 0,
    accessoryUnit: '',
    accessoryStock: '',
    companyName: '',
    manufactor: '',
    accessoryWeight: '',
    manufactorNo: '',
    lifeYear: undefined,
    factoryDate: '',
    scrapDate: '',
    status: undefined,
    comments: '',
    sortNumber: undefined,
    userId: undefined,
    createTime: '',
    updateTime: ''
  });

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单验证规则
  const rules = reactive({
    accessoryCategory: [
      {
        required: true,
        type: 'array',
        message: '请输入配件分类',
        trigger: 'blur'
      }
    ],
    accessoryName: [
      {
        required: true,
        type: 'string',
        message: '请输入配件名称',
        trigger: 'blur'
      }
    ],
    accessoryModel: [
      {
        required: true,
        type: 'string',
        message: '请输入设备型号',
        trigger: 'blur'
      }
    ],
    accessoryWeight: [
      {
        required: true,
        type: 'string',
        message: '请输入设备重量',
        trigger: 'blur'
      }
    ],
    accessorySpecs: [
      {
        required: true,
        type: 'string',
        message: '请输入设备规格',
        trigger: 'blur'
      }
    ],
    accessoryUnit: [
      {
        required: true,
        type: 'string',
        message: '请输入单位',
        trigger: 'blur'
      }
    ]
  });

  const { resetFields } = useForm(form, rules);
  const chooseCompanyName = (data: Customer) => {
    form.companyName = data.customerName;
  };
  const chooseAccessoryModel = (data: TowerModel) => {
    form.accessoryModel = data.name?.concat(String(data.model));
    form.lifeYear = data.yearLife;
  };
  const chooseMultiple = (data) => {
    form.accessoryModelMultiple = [];
    data.map((d) => {
      form.accessoryModelMultiple?.push(`${d.name}${d.model}`);
    });
  };

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        console.log(form.accessoryCategory?.[0]);
        const formData = {
          ...form,
          accessoryCategory: `${form.accessoryCategory?.[0]} / ${form.accessoryCategory?.[1]}`,
          accessoryModelMultiple: JSON.stringify(form.accessoryModelMultiple)
        };
        const saveOrUpdate = isUpdate.value ? updateAccessory : addAccessory;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignObject(form, props.data);
          const accessoryCategory = String(props.data.accessoryCategory);
          const split = accessoryCategory?.split(' / ');
          if (typeof split == 'object') {
            form.accessoryCategory = split;
          }
          if (props.data.accessoryModelMultiple) {
            form.accessoryModelMultiple = JSON.parse(
              String(form.accessoryModelMultiple)
            );
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    }
  );
</script>
<style lang="less">
  .tab-pane {
    min-height: 300px;
  }
  .ml-10 {
    margin-left: 5px;
  }
  .upload-text {
    margin-right: 70px;
  }
</style>
