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

const remoteSelectRef = ref<any>(null);

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

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

const initalFormData = {
  cat_code: "",
  cat_name: "",
  inv_good_name: "",
  tax: "",
  inv_tag: "",
  is_discount: "",
  addTax: ""
};

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 state = computed(() => ({
  //是否包含优惠政策
  isDiscount: formData.is_discount === "1",
  //税率是否为0
  isZeroTaxRate: formData.tax === "0%"
}));

//禁用字段
const disabledField = computed(() => {
  const isDisabledTaxField = !formData.cat_code;
  const { isDiscount, isZeroTaxRate } = state.value;

  return {
    tax: isDisabledTaxField,
    is_discount: isDisabledTaxField,
    //非零税率没有优惠政策禁用
    addTax: isDisabledTaxField || !isZeroTaxRate || !isDiscount,
    //非零税率禁用 有优惠政策且零税率
    inv_tag:
      isDisabledTaxField || !isZeroTaxRate || (isDiscount && isZeroTaxRate)
  };
});

//动态验证规则
const dynamicRules = computed(() => {
  const { isDiscount, isZeroTaxRate } = state.value;
  return {
    ...cost_rules,
    //汇率标识是否必填(零税率)
    inv_tag: [{ ...cost_rules.inv_tag, required: isZeroTaxRate }],
    //增值税管理是否必填(有优惠政策且零税率)
    addTax: [{ ...cost_rules.addTax, required: isDiscount && isZeroTaxRate }]
  };
});

const dynamicOptions = computed(() => {
  const { isDiscount, isZeroTaxRate } = state.value;
  let addTax = [];
  let invTag = [];

  if (isDiscount && isZeroTaxRate) {
    invTag = addTax = [inv_tag[0], inv_tag[1]];
  }

  if (isZeroTaxRate && !isDiscount) {
    invTag = [inv_tag[2]];
  }

  return { addTax, invTag };
});

function handleRelatedCategories() {
  formRef.value.validate(async isValid => {
    if (!isValid) return;

    const { addTax, is_discount, inv_tag, cat_code, inv_good_name, tax } =
      formData;
    console.log(addTax + "-----" + inv_tag);
    const list = [
      {
        addTax,
        is_discount,
        inv_tag: inv_tag || "0",
        cat_code,
        inv_good_name,
        tax,
        spuCode: spuCode.value
      }
    ];

    loading.value = true;
    const { code, message } = await httpAdd({ list, status: "2", isZx: props.isZx ? '1' : '0' });
    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, cat_name } = category;
  formData.cat_name = cat_name;
  taxs.value = [...tax, "0%", "1%", "3%"];

  if(!isInit){
    formData.tax = "";
    formData.addTax = "";
    formData.inv_tag = "";
    formData.is_discount = "";
  }
}

//优惠政策改变清空增值税管理和汇率标识
const handleDiscountChange = () => {
  formData.addTax = "";
  formData.inv_tag = "";
};

//税率改变清空增值税管理和汇率标识
const handleTaxChange = () => {
  formData.is_discount = "";
  formData.addTax = "";
  formData.inv_tag = "";
};

watch(
  () => formData.addTax,
  addTax => {
    if (!addTax) return;
    //零税率且有优惠政策时需要同步增值税管理和汇率标识的值
    const { isZeroTaxRate, isDiscount } = state.value;
    if (isZeroTaxRate && isDiscount) {
      const list: Array<T> = dynamicOptions.value.addTax;
      let index = list.findIndex(item => item.label === formData.addTax);
      formData.inv_tag = list[index].value;
    }
  },
  {
    immediate: true
  }
);

watch(
  () => [props.detail, remoteSelectRef.value],
  async () => {
    if (!props.detail || !remoteSelectRef.value) return;
    const {
      cgd_inv_good_name,
      cgd_inv_cat_code,
      inv_cat_code,
      is_discount,
      good_name,
      cgd_inv_tax,
      inv_tax,
      inv_tag,
      addTax,
      status
    } = props.detail;

    formData.inv_good_name = cgd_inv_good_name ? cgd_inv_good_name : good_name;
    formData.tax = cgd_inv_tax ? cgd_inv_tax : "";
    formData.is_discount = String(is_discount);

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

    nextTick(() => {
      formData.inv_tag = String(inv_tag) !== "0" ? String(inv_tag) : "";
      formData.addTax = addTax;
    });

    if (Number(status) === 1 && cgd_inv_cat_code && remoteSelectRef.value) {
      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%'];
    }


   

    if (Number(status) === 2 && remoteSelectRef.value) {
      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%'];
      formData.tax = inv_tax;
      formData.is_discount = String(is_discount);
      formData.inv_tag = String(inv_tag) !== "0" ? String(inv_tag) : "";
      formData.addTax = addTax;
    }
  },
  {
    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
          :api="httpCatlist"
          v-model="formData.cat_code"
          :getLabel="handleLabel"
          placeholder="请选择商品类目"
          response-label-prop="cat_name"
          response-val-prop="merge_code"
          request-prop="cat_name"
          sub-label-prop="short_name"
          @item-change="handleSelectCategory"
          loadMore
          @inital="code => (formData.cat_code = code)"
        /> -->
        <QueryCategory 
            ref="remoteSelectRef"
            v-model="formData.cat_code"
            @change="handleSelectCategory"
            classWrapper="finance-item"
          />
      </el-form-item>
    </div>

    <div>
      <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="请输入税率"
          @change="handleTaxChange"
        >
          <el-option
            v-for="(t, index) in taxs"
            :key="index"
            :label="t"
            :value="t"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="是否有优惠政策" prop="is_discount">
        <el-select
          :disabled="disabledField.is_discount"
          w-150px
          v-model="formData.is_discount"
          placeholder="请选择是否包含优惠政策"
          @change="handleDiscountChange"
        >
          <el-option label="否" value="0" />
          <el-option label="是" value="1" />
        </el-select>
      </el-form-item>

      <el-form-item label="增值税管理内容" prop="addTax">
        <el-select
          :disabled="disabledField.addTax"
          w-230px
          v-model="formData.addTax"
          placeholder="请选择增值税管理税内容"
        >
          <el-option
            v-for="(t, i) in dynamicOptions.addTax"
            :key="i"
            :label="t.label"
            :value="t.label"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="汇率标识" prop="inv_tag">
        <el-select
          w-180px
          :disabled="disabledField.inv_tag"
          v-model="formData.inv_tag"
          placeholder="请选择汇率标识"
        >
          <el-option
            v-for="(tag, index) in dynamicOptions.invTag"
            :key="index"
            :label="tag.label"
            :value="tag.value"
          />
        </el-select>
      </el-form-item>
    </div>
  </el-form>

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

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