<template>
    <div id="product-form">
        <el-form
            :model="productForm"
            :rules="productFormRules"
            ref="productForm"
            label-width="120px"
        >
            <el-form-item style="text-align: left;">
                <div style="background-color: gray; padding: 5px 10px;">
                    <span style="color: white;">使用提示：“产品分类”的填写内容需要使用商品搜索功能，选择商品后自动填写！</span>
                    <el-button type="primary" @click="showZNFMSearchProductDialog">商品智能赋码</el-button>
                    <el-button
                        type="primary"
                        @click="showSDFMSearchProductDialog"
                        style="margin-left: 10px;"
                    >手动赋码</el-button>
                </div>
            </el-form-item>
            <el-form-item label="税收分类编码" prop="taxationCateCode">
                <el-input v-model="productForm.taxationCateCode" placeholder="查询后自动填入或手动输入"></el-input>
            </el-form-item>
            <el-form-item label="税收分类简称" prop="taxationCateAbbr">
                <el-input v-model="productForm.taxationCateAbbr" placeholder="查询后自动填入或手动输入"></el-input>
            </el-form-item>
            <el-form-item label="税收商品名称" prop="taxationCateName">
                <el-input v-model="productForm.taxationCateName" placeholder="查询后自动填入或手动输入"></el-input>
            </el-form-item>
            <el-form-item label="产品名称" prop="productName">
                <el-input v-model="productForm.productName" v-on:input="productNamePinyin"></el-input>
            </el-form-item>
            <el-form-item label="简码">
                <el-input v-model="productForm.shortCode" readonly="readonly"></el-input>
            </el-form-item>
            <el-form-item label="规格">
                <el-input v-model="productForm.specsModel"></el-input>
            </el-form-item>
            <el-form-item label="计量单位">
                <el-input v-model="productForm.unit"></el-input>
            </el-form-item>
            <el-form-item label="单价" prop="price">
                <el-input-number
                    v-model="productForm.price"
                    :min="0"
                    :controls="false"
                    :precision="6"
                ></el-input-number>
            </el-form-item>
            <el-form-item label="税率" prop="taxRate" style="text-align: left;">
                <el-select
                    v-model="productForm.taxRate"
                    :disabled="productForm.taxRateDisabled"
                    placeholder="请选择"
                    @change="handleTaxRateChange()"
                >
                    <el-option
                        v-for="item in commodityTaxRate"
                        :key="item"
                        :label="Number.parseFloat(item) * 100 + '%'"
                        :value="item"
                    ></el-option>
                </el-select>
                <el-button @click="handleGetEntTaxRates" style="margin-left: 10px;">刷新</el-button>
            </el-form-item>
            <el-form-item label="零税率标识" prop="zeroRateFlag" style="text-align: left;">
                <el-select
                    v-model="productForm.zeroRateFlag"
                    :disabled="productForm.zeroRateFlagDisabled"
                    placeholder="请选择"
                    @change="handleZeroRateFlagChange()"
                >
                    <el-option
                        v-for="item in zeroRateFlagOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                        :disabled="item.disabled"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="优惠政策标识" prop="preferentialFlag" style="text-align: left;">
                <el-select
                    v-model="productForm.preferentialFlag"
                    placeholder="请选择"
                    @change="handlePreferentialFlagChange"
                >
                    <el-option
                        v-for="item in preferentialFlagOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item
                v-if="preferentialTypeVisible"
                label="优惠政策类型"
                prop="preferentialType"
                style="text-align: left;"
            >
                <el-select
                    v-model="productForm.preferentialType"
                    placeholder="请选择"
                    @change="handlePreferentialTypeChange"
                >
                    <el-option
                        v-for="(item, index) in preferentials"
                        :key="index"
                        :label="item.label"
                        :value="item.label"
                    ></el-option>
                </el-select>
                <el-button @click="handleGetPreferentials" style="margin-left: 10px;">刷新</el-button>
            </el-form-item>
        </el-form>

        <el-dialog
            title="智能赋码商品查询"
            :visible.sync="znfmSearchProduct.dialogVisible"
            width="50%"
            center
            append-to-body
        >
            <el-row type="flex" :gutter="20">
                <el-col :span="16">
                    <el-input
                        v-model="znfmSearchProduct.search.productName"
                        clearable
                        prefix-icon="el-icon-search"
                        placeholder="请输入商品名称"
                    ></el-input>
                </el-col>
                <el-col :span="8">
                    <el-button @click="handleZNFMSearchProduct" type="primary">搜索</el-button>
                </el-col>
            </el-row>
            <br />
            <el-container>
                <el-table
                    :data="znfmSearchProduct.search.resultList"
                    border
                    style="width: 100%;"
                    height="350px"
                >
                    <el-table-column prop="code" label="商品分类编码" width="180" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="name" label="商品名称" width="180" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="shortName" label="简称" width="180" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="desc" label="描述" width="240" show-overflow-tooltip></el-table-column>
                    <el-table-column fixed="right" label="操作" align="center">
                        <template slot-scope="scope" width="100">
                            <el-button
                                @click="handleZNFMSelecteProduct(scope.row)"
                                type="primary"
                            >使用</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-container>
        </el-dialog>

        <el-dialog
            title="手动赋码商品查询"
            :visible.sync="sdfmSearchProduct.dialogVisible"
            width="55%"
            center
            append-to-body
        >
            <el-container>
                <el-aside width="350px">
                    <div style="100%">
                        <el-row :gutter="10">
                            <el-col :span="14">
                                <el-input
                                    v-model="sdfmSearchProduct.search.productName"
                                    prefix-icon="el-icon-search"
                                    placeholder="输入关键字进行搜索"
                                ></el-input>
                            </el-col>
                            <el-col :span="10">
                                <el-button type="primary" @click="handleSDFMSearchProduct">搜索</el-button>
                                <el-button @click="handleSDFMResetTree">重置</el-button>
                            </el-col>
                        </el-row>
                    </div>
                    <br />
                    <el-scrollbar style="width: 100%; height: 500px;">
                        <el-tree
                            v-show="sdfmSearchProduct.search.showSearchTree"
                            :data="sdfmSearchProduct.search.resultList"
                            :props="sdfmSearchProduct.props"
                            :highlight-current="true"
                            :default-expand-all="true"
                            @node-click="handleSDFMSelecteProduct"
                            style="width: 500px;"
                        ></el-tree>
                        <el-tree
                            v-show="!sdfmSearchProduct.search.showSearchTree"
                            :data="sdfmSearchProduct.productList"
                            :props="sdfmSearchProduct.props"
                            :highlight-current="true"
                            lazy
                            :load="handleLoadSDFMNode"
                            @node-click="handleSDFMSelecteProduct"
                            style="width: 500px;"
                        ></el-tree>
                    </el-scrollbar>
                </el-aside>
                <el-main style="background-color: #f8f8ff; margin-left: 20px;">
                    <el-row :gutter="20">
                        <el-col :span="24">
                            <div>商品分类编码：</div>
                            <br />
                            <el-input v-model="sdfmSearchProduct.selectNode.code" :readonly="true"></el-input>
                        </el-col>
                    </el-row>
                    <br />
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <div>商品名称：</div>
                            <br />
                            <el-input v-model="sdfmSearchProduct.selectNode.name" :readonly="true"></el-input>
                        </el-col>
                        <el-col :span="12">
                            <div>简称：</div>
                            <br />
                            <el-input
                                v-model="sdfmSearchProduct.selectNode.cateName"
                                :readonly="true"
                            ></el-input>
                        </el-col>
                    </el-row>
                    <br />
                    <el-row :gutter="20">
                        <el-col :span="24">
                            <div>税率：</div>
                            <br />
                            <el-input v-model="sdfmSearchProduct.selectNode.rate" :readonly="true"></el-input>
                        </el-col>
                    </el-row>
                    <br />
                    <el-row :gutter="20">
                        <el-col :span="24">
                            <div>描述：</div>
                            <br />
                            <el-input
                                type="textarea"
                                :rows="5"
                                v-model="sdfmSearchProduct.selectNode.desc"
                                :readonly="true"
                            ></el-input>
                        </el-col>
                    </el-row>
                </el-main>
            </el-container>
            <el-divider style="margin: 0, 10;"></el-divider>
            <div style="text-align: right;">
                <el-button
                    @click="sdfmSearchProduct.dialogVisible = false"
                    style="margin-left: 10px;"
                >取消</el-button>
                <el-button type="primary" @click="handleSDFMOk" style="margin-left: 10px;">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {
    znfmCommoditySearch,
    getEntTaxRates,
    getPreferentials,
} from "@/api/user_config";

import {
    GetProductChildCateCodes,
    GetProductCateCodeTree,
} from "@/api/product";

// 零税率标识选项列表
const zeroRateFlagOptions = [
    {
        value: null,
        label: "无",
        disabled: false,
    },
    {
        value: 1,
        label: "免税",
        disabled: true, // 不提供选择
    },
    {
        value: 2,
        label: "不征税",
        disabled: true, // 不提供选择
    },
    {
        value: 3,
        label: "普通零税率",
        disabled: false,
    },
];

// 优惠政策标识选项列表
const preferentialFlagOptions = [
    {
        value: 1,
        label: "使用",
    },
    {
        value: 0,
        label: "不使用",
    },
];

// 产品表单的默认值
const productFormDefault = {
    taxationCateCode: "",
    taxationCateName: "",
    taxationCateAbbr: "",
    taxPriceFlag: true,
    productId: "", // 修改时使用；
    productName: "",
    shortCode: "",
    specsModel: "",
    unit: "",
    price: 0,
    taxRate: "",
    taxRateDisabled: false, // 是否禁用
    zeroRateFlag: null, // 默认选中“无”
    zeroRateFlagDisabled: false, // 是否禁用
    preferentialFlag: "",
    preferentialType: "",
};

export default {
    name: "ProductForm",
    props: {
        // 1.输入已经存在的客户信息，用于编辑客户信息
        // 2.用于覆盖已有数据
        inputProductInfo: {
            type: Object,
            default: null,
        },
    },
    data() {
        var checkZeroRateFlag = (rule, value, callback) => {
            if (value === "") {
                return callback(new Error("请选择零税率标识！"));
            }
            callback();
        };
        return {
            zeroRateFlagOptions: zeroRateFlagOptions,
            preferentialFlagOptions: preferentialFlagOptions,
            preferentials: [], // 优惠政策类型列表
            commodityTaxRate: [], // 商品税率
            productForm: { ...productFormDefault },
            productFormRules: {
                taxationCateCode: [
                    {
                        required: true,
                        message: "请输入税收分类编码",
                        trigger: "change",
                    },
                ],
                taxationCateName: [
                    {
                        required: true,
                        message: "请输入税收商品名称",
                        trigger: "change",
                    },
                ],
                taxationCateAbbr: [
                    {
                        required: true,
                        message: "请输入税收分类简称",
                        trigger: "change",
                    },
                ],
                productName: [
                    {
                        required: true,
                        message: "请输入产品名称",
                        trigger: "change",
                    },
                ],
                taxRate: [
                    {
                        required: true,
                        message: "请选择税率！",
                        trigger: "change",
                    },
                ],
                zeroRateFlag: [
                    {
                        required: true,
                        validator: checkZeroRateFlag,
                        trigger: "change",
                    },
                ],
                preferentialFlag: [
                    {
                        required: true,
                        message: "请选择优惠政策标识！",
                        trigger: "change",
                    },
                ],
                preferentialType: [
                    {
                        required: true,
                        message: "请选择优惠政策类型！",
                        trigger: "change",
                    },
                ],
            },
            znfmSearchProduct: {
                dialogVisible: false,
                search: {
                    productName: "", // 产品名称
                    resultList: [], // 查询结果列表
                },
            },
            sdfmSearchProduct: {
                dialogVisible: false,
                productList: [], // 商品列表
                props: {
                    label: "name",
                    children: "children",
                },
                search: {
                    showSearchTree: false,
                    productName: "", // 产品名称
                    resultList: [], // 查询结果列表
                },
                selectNode: {
                    code: "",
                    name: "",
                    cateName: "",
                    rate: "",
                    desc: "",
                },
            },
        };
    },
    watch: {
        inputProductInfo(val) {
            this.updateProductForm(val);
        },
    },
    computed: {
        preferentialTypeVisible() {
            // 优惠政策标识是“使用”时，显示优惠政策类型；
            if (this.productForm.preferentialFlag === 1) {
                // this.handleGetPreferentials();
                return true;
            } else {
                // this.preferentials = [];
                return false;
            }
        },
    },
    methods: {
        updateProductForm(val) {
            if (val == null || JSON.stringify(val) == "{}") {
                this.productForm = { ...productFormDefault };
            } else {
                this.productForm = { ...val };
                // 特殊处理，
                // 不使用优惠政策，优惠政策类型值为空字符串；
                if (this.productForm.preferentialFlag == 0) {
                    this.productForm.preferentialType = "";
                }
                let _this = this;
                getPreferentials()
                    .then((val) => {
                        _this.preferentials = val.data;
                        // 特殊处理，如果优惠政策类型有值，
                        // 税率可能不可修改；
                        _this.handlePreferentialTypeChange();
                    })
                    .catch((err) => {
                        _this.preferentials = [];
                        _this.$message.error(err);
                    });
            }
            this.commodityTaxRate = [];
        },
        // 获取税率
        handleGetEntTaxRates() {
            if (this.productForm.taxationCateCode) {
                getEntTaxRates(this.productForm.taxationCateCode)
                    .then((val) => {
                        this.commodityTaxRate = val.data;
                    })
                    .catch((err) => {
                        this.commodityTaxRate = [];
                        this.$message.error(err);
                    });
            }
        },
        handleGetPreferentials() {
            getPreferentials()
                .then((val) => {
                    this.preferentials = val.data;
                })
                .catch((err) => {
                    this.preferentials = [];
                    this.$message.error(err);
                });
        },
        showZNFMSearchProductDialog() {
            this.znfmSearchProduct.dialogVisible = true;
        },
        handleZNFMSearchProduct() {
            let productName = this.znfmSearchProduct.search.productName;
            if (productName != "") {
                znfmCommoditySearch(productName)
                    .then((val) => {
                        this.znfmSearchProduct.search.resultList = val.data;
                    })
                    .catch((err) => {
                        this.$message.error(err);
                    });
            }
        },
        handleZNFMSelecteProduct(row) {
            this.productForm.taxationCateCode = row.code;
            this.productForm.taxationCateName = row.name;
            this.productForm.taxationCateAbbr = row.shortName;
            this.commodityTaxRate = row.sortedRateSet;

            this.znfmSearchProduct.dialogVisible = false;
        },
        showSDFMSearchProductDialog() {
            this.sdfmSearchProduct.dialogVisible = true;
        },
        handleSDFMSearchProduct() {
            let productName = this.sdfmSearchProduct.search.productName;
            if (productName != "") {
                this.sdfmSearchProduct.search.showSearchTree = true;
                // 清空tree
                this.sdfmSearchProduct.search.resultList = [];
                GetProductCateCodeTree(productName)
                    .then((val) => {
                        this.sdfmSearchProduct.search.resultList = this.getSDFMOriginalChildren(
                            val.data
                        );
                    })
                    .catch((err) => {
                        this.$message.error(err);
                    });
            } else {
                this.sdfmSearchProduct.search.showSearchTree = false;
            }
        },
        handleSDFMResetTree() {
            this.sdfmSearchProduct.search.productName = "";
            this.sdfmSearchProduct.search.resultList = [];
            this.sdfmSearchProduct.search.showSearchTree = false;
        },
        // 获取手动赋码原数据的信息。
        getSDFMOriginalChildren(children) {
            let fmtNode = [];
            for (const item of children) {
                let tempNode = {
                    name: item.name,
                    original: item, // 自定义添加字段，存储节点原始信息
                };
                if (item.children != null && item.children.length > 0) {
                    tempNode.children = this.getSDFMOriginalChildren(
                        item.children
                    );
                }
                fmtNode.push(tempNode);
            }
            return fmtNode;
        },
        handleLoadSDFMNode(node, resolve) {
            let parentCode = "";
            if (node.level !== 0) parentCode = node.data.original.code;
            return this.callGetProductChildCateCodes(parentCode, resolve);
        },
        handleSDFMSelecteProduct(data, node) {
            // if (!node.isLeaf) return
            if (node.data.original != null) {
                this.sdfmSearchProduct.selectNode.code =
                    node.data.original.code;
                this.sdfmSearchProduct.selectNode.name =
                    node.data.original.name;
                this.sdfmSearchProduct.selectNode.cateName =
                    node.data.original.cateName;
                this.sdfmSearchProduct.selectNode.rate =
                    node.data.original.rate;
                this.sdfmSearchProduct.selectNode.desc =
                    node.data.original.desc;
            }
        },
        handleSDFMOk() {
            if (!this.sdfmSearchProduct.selectNode.code) {
                this.$message.error("请选择商品分类项目！");
                return false;
            }
            if (
                this.sdfmSearchProduct.selectNode.rate == null ||
                this.sdfmSearchProduct.selectNode.rate == ""
            ) {
                this.$message.error("选择商品分类项目不是末级项目！");
                return false;
            }
            getEntTaxRates(this.sdfmSearchProduct.selectNode.code)
                .then((val) => {
                    this.productForm.taxationCateCode = this.sdfmSearchProduct.selectNode.code;
                    this.productForm.taxationCateName = this.sdfmSearchProduct.selectNode.name;
                    this.productForm.taxationCateAbbr = this.sdfmSearchProduct.selectNode.cateName;
                    this.commodityTaxRate = val.data;

                    this.sdfmSearchProduct.dialogVisible = false;
                })
                .catch((err) => {
                    this.$message.error(err + ",您可以稍后重试！");
                });
        },
        callGetProductChildCateCodes(parentCode, resolve) {
            let resultNodes = new Array();
            GetProductChildCateCodes(parentCode)
                .then((val) => {
                    if (val.data != null && val.data.length > 0) {
                        for (const item of val.data) {
                            resultNodes.push({
                                name: item.name,
                                original: item, // 自定义添加字段，存储节点原始信息
                            });
                        }
                    }
                    resolve(resultNodes);
                })
                .catch((err) => {
                    this.$message.error(err);
                    resolve([]);
                });
        },
        handleTaxRateChange() {
            console.log("handleTaxRateChange");
            if (this.productForm.taxRate === 0) {
                // 手动选择0%
                // 1.零税率标识控件 → 普通零税率；
                // 2.优惠政策标识控件 → 重置到未选择状态；
                // 3.优惠政策类型控件 → 隐藏；
                // 4.优惠政策类型控件 → 重置到未选择状态；
                this.productForm.zeroRateFlag = 3;
                this.productForm.preferentialFlag = "";
                this.productForm.preferentialType = "";
            } else {
                // 其它情况，零税率标识→选择“无”
                this.productForm.zeroRateFlag = null;
            }
        },
        handleZeroRateFlagChange() {
            console.log("handleZeroRateFlagChange");

            // 零税率标识改变，联动：
            // 1.优惠政策标识控件 → 重置到未选择状态；
            // 2.优惠政策类型控件 → 重置到未选择状态；
            // 3.优惠政策类型控件 → 隐藏；
            this.productForm.preferentialFlag = "";
            this.productForm.preferentialType = "";

            // 根据选中项特殊处理
            if (this.productForm.zeroRateFlag == null) {
                // 零税率标识→选择“无”
                // 1.税率控件 → 可使用；
                // 2.税率控件 → 重置到未选择状态；
                this.productForm.taxRateDisabled = false;
                this.productForm.taxRate = "";
            } else if (this.productForm.zeroRateFlag == 3) {
                // 零税率标识→选择“普通零税率”
                // 1.税率控件 → 禁用；
                // 2.税率控件 → 税率设置为“0”；
                this.productForm.taxRateDisabled = true;
                this.productForm.taxRate = 0;
            }
        },
        handlePreferentialFlagChange() {
            console.log("handlePreferentialFlagChange");
            if (this.productForm.preferentialFlag == 1) {
                // 优惠政策标识，选择“使用”
                // 1.税率控件 → 不影响；
                // 2.零税率标识控件 → 不影响
                // 3.优惠政策类型控件 → 显示；
            } else if (this.productForm.preferentialFlag == 0) {
                // 优惠政策标识，选择“不使用”
                // 1.税率控件 → 不影响；
                // 2.零税率标识控件 → 不影响；
                // 3.优惠政策类型控件 → 隐藏；
                this.productForm.preferentialType = "";
            }
        },
        handlePreferentialTypeChange() {
            console.log("handlePreferentialTypeChange");
            let tempOption = null;
            for (const item of this.preferentials) {
                if (item.label === this.productForm.preferentialType) {
                    tempOption = item;
                    break;
                }
            }
            if (tempOption != null) {
                console.log("tempOption：");
                console.log(tempOption);

                // limit:税率控件 → 禁用，使用优惠政策类型中的“rate”字段设置税率，
                // none:税率控件 → 可使用，税率控件中的值删除；
                this.productForm.taxRateDisabled = tempOption.op == "limit";
                this.productForm.taxRate = tempOption.rate
                    ? tempOption.rate
                    : "";

                if (
                    this.productForm.zeroRateFlag === 1 ||
                    this.productForm.zeroRateFlag === 2
                ) {
                    // 零税率标识为“免税”或“不征税”：零税率标识控件 → 下拉值选择“无”；
                    this.productForm.zeroRateFlag = null;
                } else {
                    // 优惠政策类型的“zeroFlagIndex”字段值有效：零税率标识控件 → 设置为“zeroFlagIndex”字段有效值；
                    // 否则：零税率标识控件 → 无影响；
                    if (tempOption.zeroFlagIndex)
                        this.productForm.zeroRateFlag =
                            tempOption.zeroFlagIndex;
                }
            }
        },
        /**
         * 对外暴露获取数据的方法，内部进行表单的校验，父组件中通过refs调用
         */
        getProductInfo() {
            let _this = this;
            return new Promise((resolve, reject) => {
                _this.$refs["productForm"].validate((valid) => {
                    if (valid) {
                        resolve({ ..._this.productForm });
                    } else {
                        reject("输入信息不合法，请检查您的输入信息！");
                    }
                });
            });
        },
        /**
         * 对外暴露取消表单验证提示的方法
         */
        resetFormFields() {
            // 取消验证提示
            this.$refs["productForm"].resetFields();
        },
        // 产品名称转化为拼音
        productNamePinyin() {
            let pinyin = require("pinyin");
            let productName = pinyin(this.productForm.productName, {
                style: pinyin.STYLE_FIRST_LETTER,
            });
            let shortCode = "";
            productName.map((_, i) => {
                productName[i].map((_, l) => {
                    shortCode += productName[i][l].toUpperCase();
                });
            });
            this.productForm.shortCode = shortCode;
        },
    },
    mounted() {
        this.updateProductForm(this.inputProductInfo);
    },
};
</script>

<style scoped>
</style>
