<script setup lang="ts">
import { computed, reactive, ref, watch, shallowRef, nextTick  } from "vue";
import { cost_rules } from "./../supplyCommodityCost/config/configs";
import RemoteSelect from "/@/components/RemoteSelect";
import { useResponseHandle } from "/@/hooks";
import { useRoute } from "vue-router";
import { ElForm } from "element-plus";
import { httpCatlist, httpAdd } from "/@/api/InvoiceSaleSettings/commodityCost";

import QueryCategory from "./query-category.vue"

import { type DescriptionColumn } from "/@/components/BasicDescriptions";

const remoteSelectRef = ref<any>(null);

const emit = defineEmits(["refresh"]);

const props = defineProps<{
  columns: Array<DescriptionColumn>;
  backRoute: string;
  name?: string;
  detail: any;
}>();

const initalFormData = {
  inv_good_name: "", // 开票商品名称
  cat_name: "",
  cat_code: "",
  tax: ""
};

const taxs = ref<Array<string>>([]);
const { query } = useRoute();

const responseHandle = useResponseHandle();
const formRef = ref<InstanceType<typeof ElForm>>(null);
const spuCode = computed(() => query.id as string);
const formData = reactive({ ...initalFormData });

const loading = shallowRef(false);

//禁用字段
const disabledField = computed(() => {
  const isDisabledTaxField = !formData.cat_code;
  return {
    tax: isDisabledTaxField
  };
});

//动态验证规则
const dynamicRules = computed(() => {
  return {  ...cost_rules};
});

function handleRelatedCategories() {
  formRef.value.validate(async isValid => {
    if (!isValid) return;
    const { cat_code, inv_good_name, tax } = formData;
    const list = [{ cat_code, inv_good_name, tax, spuCode: spuCode.value }]

    loading.value = true;
    const { code, message } = await httpAdd({ list, status:"1" });
    loading.value = false;

    responseHandle({
      code,
      message,
      handler: () => emit("refresh")
    });
  });
}

function handleSelectCategory(category, isInit) {
  if (!category) {
    formData.tax = "";
    formData.cat_name = "";
    return (taxs.value = []);
  }

  const { tax, label } = category;
  taxs.value = [...tax, "0%"];

  if(!isInit){
    formData.cat_name = label;
    formData.tax = "";
  }
}

watch(
  () => props.detail,
  async () => {
      if (!props.detail) return;
    const { inv_good_name, inv_cat_code, good_name, inv_tax, cgd_inv_tax, cgd_inv_cat_code } = props.detail;

    formData.inv_good_name = inv_good_name ? inv_good_name : good_name;
    formData.tax = inv_tax ? inv_tax * 100 + "%" : "";


    if (formData.inv_good_name.length > 70) {
      formData.inv_good_name = formData.inv_good_name.slice(0, 70);
    }

    if (cgd_inv_tax) {
        formData.tax = cgd_inv_tax;
      }

    nextTick(async () => {
      if (inv_cat_code && remoteSelectRef.value && inv_cat_code.trim().length !== 0) {
        const params = { cat_code: inv_cat_code };
        const result = await remoteSelectRef.value.initalData(params);
        if (!result || !Array.isArray(result)) return;
        const { tax } = result[0];
        taxs.value = [...tax, '0%','1%','3%'];
      } else if (cgd_inv_cat_code && remoteSelectRef.value && cgd_inv_cat_code.trim().length !== 0) {
        const params = { cat_code: cgd_inv_cat_code };
        const result = await remoteSelectRef.value.initalData(params);
        if (!result || !Array.isArray(result)) return;
        const { tax } = result[0];
        taxs.value = [...tax, '0%','1%','3%'];
      }
    })
  },
  {
    immediate: true
  }
);
</script>

<template>
  <el-form
    label-position="left"
    ref="formRef"
    :rules="dynamicRules"
    :model="formData"
  >
    <div flex gap="1">
      <el-form-item label="商品类目设置" prop="cat_code" flex-1>
        <!-- <RemoteSelect
          ref="remoteSelectRef"
          w-full
          is-root
          :api="httpCatlist"
          v-model="formData.cat_code"
          placeholder="请选择商品类目"
          response-label-prop="cat_name"
          response-val-prop="merge_code"
          request-prop="cat_name"
          sub-label-prop="short_name"
          @item-change="handleSelectCategory"
          @inital="code => (formData.cat_code = code)"
        /> -->

        <QueryCategory 
            ref="remoteSelectRef"
            v-model="formData.cat_code"
            @change="handleSelectCategory"
          />
      </el-form-item>
      <el-form-item label="开票商品名称" prop="inv_good_name" flex-1>
        <el-input
          w-full
          v-model="formData.inv_good_name"
          placeholder="请输入商品名称"
          maxlength="70"
        />
      </el-form-item>
    </div>

    <div flex gap-3>
      <el-form-item label="税率" prop="tax">
        <el-select
          w-180px
          v-model="formData.tax"
          :disabled="disabledField.tax"
          placeholder="请输入税率"
        >
          <el-option
            v-for="(t, index) in taxs"
            :key="index"
            :label="t"
            :value="t"
          />
        </el-select>
      </el-form-item>
    </div>
  </el-form>

  <div flex justify-end>
    <el-button type="primary" @click="handleRelatedCategories" :loading="loading">保存</el-button>
  </div>
</template>

<style lang="scss" scoped>
.settings__content {
  padding: 20px !important;
}
</style>
