<template>
  <div>
    <div class="forms pack-rule">
      <el-table
        v-if="goodsList.length"
        :data="goodsList"
        border
        style="width: 100%; margin-bottom: 10px;"
      >
        <el-table-column prop="name" :label="$t('permission.goodsName')" />
        <el-table-column prop="price" :label="$t('permission.price')" width="100" />
        <el-table-column prop="remarks" label="描述" />
        <el-table-column v-if="goodsList[0].isPackage" :label="this.$t('global.operate')" width="180">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="showPermission(scope.$index, scope.row)">{{ $t('permission.permissionList') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <data-form ref="dataform" :form="form" :form-model="formModel" :rules="rules" class="data-box" />
    </div>
    <div class="draft">
      <el-button-group>
        <el-button type="primary" @click="back">{{ $t('permission.lastShep') }}</el-button>
        <el-button type="primary" @click="packageCode">{{ $t('permission.package') }}</el-button>
      </el-button-group>
    </div>
    <premission-list ref="permissionList" />
  </div>
</template>

<script>
import { addOrganization, getOrganizationList } from '@/api/management/organization';
import { getSellerList } from '@/api/management/user';
import { createPermission } from '@/api/management/order';
import PremissionList from './list';
// import { deepAssign } from '@/utils/index';

export default {
    name: 'OrderForm',
    components: {
        PremissionList
    },
    props: {
        permissionType: {
            type: String,
            required: true
        },
        goodsList: {
            type: Array,
            default: () => {
                return [];
            }
        }
    },
    data() {
        return {
            OrganizationList: [],
            OrderTypeList: [],
            SellerList: [],
            BizTypeList: [],
            PayTypeList: [],
            PayStatusTypeList: [],
            OrgzList: [],
            foreverInitData: false,
            canDistribute: true,
            urlInfo: {},
            goodsVo: {},
            orderList: [],
            formModel: {
                organizationId: '',
                goodsId: '',
                goodsName: '',
                orderType: '02',
                contractNo: '',
                forever: false,
                totalPrice: 0,
                price: 0,
                amount: 0,
                monthAmount: 0,
                bizType: '01',
                payWays: '01',
                payStatus: '02',
                startTime: '',
                sellerId: '',
                canDistribute: '01'
            },
            DatePicker: {
                shortcuts: [{
                    text: this.$t('orderAuthor.today'),
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: this.$t('orderAuthor.yesterday'),
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: this.$t('orderAuthor.aWeekAgo'),
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            permissionList: [
                { value: '01', label: this.$t('orderAuthor.publicAuthority') },
                { value: '02', label: this.$t('orderAuthor.privateAuthority') }
            ]
        };
    },
    computed: {
        isShowStartDate() {
            return !this.formModel.forever && (this.formModel.bizType !== '02'); // 非永久的非续费类型显示开始时间
        },
        isShowMonths() {
            return !this.formModel.forever; // 非永久类型显示月份
        },
        isShowContractNo() {
            return this.formModel.orderType === '02'; // 是合同类型显示
        },
        isShowPrice() {
            return this.formModel.orderType === '02'; // 是合同类型显示
        },
        isShowPayType() {
            return this.formModel.orderType === '02'; // 是合同类型显示
        },
        isShowPayStatus() {
            return this.formModel.orderType === '02'; // 是合同类型显示
        },
        isShowSeller() {
            return this.formModel.orderType !== '04'; // 不是内部分配显示
        },
        foreverIsDisabled() {
            return this.foreverInitData;
        },
        form() {
            const form = {
                labelWidth: this.$i18n.locale == 'en' ? '200px' : '145px',
                items: [
                    { prop: 'organizationId', label: this.$t('orderAuthor.organizationOrEnterprise'), type: 'select', options: this.OrganizationList, allowCreate: true, onChange: this.onChange },
                    { prop: 'orderType', label: this.$t('orderAuthor.orderType'), type: 'select', options: this.OrderTypeList },
                    { prop: 'sellerId', label: this.$t('orderAuthor.salesman'), type: 'select', show: this.isShowSeller, options: this.SellerList },
                    { prop: 'contractNo', label: this.$t('orderAuthor.contractNumber'), type: 'text', show: this.isShowContractNo },
                    { prop: 'amount', label: this.$t('orderAuthor.choosePermissionNumber'), type: 'number', show: true, min: 0 },
                    { prop: 'forever', label: this.$t('orderAuthor.permanenceOrNot'), type: 'radio', options: this.$ConstSelect.Whether, disabled: this.foreverIsDisabled },
                    { prop: 'startTime', label: this.$t('orderAuthor.startDate'), type: 'date', show: this.isShowStartDate, viewFormat: 'yyyy-MM-dd', valueFormat: 'yyyy-MM-dd', picker: this.DatePicker },
                    { prop: 'monthAmount', label: this.$t('orderAuthor.choosePurchaseTime'), type: 'number', show: this.isShowMonths, min: 0, message: this.$t('orderAuthor.month') },
                    { prop: 'totalPrice', label: this.$t('orderAuthor.totalPrice'), type: 'number', show: this.isShowPrice, min: 0, message: this.$t('orderAuthor.yuan') },
                    { prop: 'bizType', label: this.$t('orderAuthor.businessType'), type: 'select', disabled: true, options: this.BizTypeList },
                    { prop: 'payWays', label: this.$t('orderAuthor.paymentMethod'), type: 'select', show: this.isShowPayType, options: this.PayTypeList },
                    { prop: 'payStatus', label: this.$t('orderAuthor.paymentStatus'), type: 'select', show: this.isShowPayStatus, options: this.PayStatusTypeList },
                    { prop: 'canDistribute', label: this.$t('orderAuthor.optionPrivilegeTransfer'), type: 'radio', options: this.permissionList }
                ]
            };
            return form;
        },
        rules() {
            const _this = this;
            const baseRules = {
                organizationId: [
                    { required: true, message: this.$t('rules.organizationInput'), trigger: 'blur' }
                ],
                orderType: [
                    { required: true, message: this.$t('rules.orderTypeSelect'), trigger: 'change' }
                ],
                contractNo: [
                    { required: true, message: this.$t('rules.contractNumberInput'), trigger: 'blur' },
                    { min: 1, max: 25, message: this.$t('rules.strLength1To25'), trigger: 'blur' }
                ],
                sellerId: [
                    { required: true, message: this.$t('rules.salesmanInput'), trigger: 'change' }
                ],
                forever: [
                    { required: true, message: this.$t('rules.pleaseSelect'), trigger: 'change' }
                ],
                amount: [
                    { required: true, message: this.$t('rules.authorAmountInput'), trigger: 'change' },
                    {
                        validator(rule, value, callback) {
                            if (Number.isInteger(Number(value)) && Number(value) > 0) {
                                callback();
                            } else {
                                callback(new Error(_this.$t('rules.authorAmountInputError')));
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                totalPrice: [
                    { required: true, message: this.$t('rules.totalPriceInput'), trigger: 'change' },
                    {
                        validator(rule, value, callback) {
                            if (Number(value) >= 0) {
                                if (String(value).split('.')[1] && String(value).split('.')[1].length > 2) {
                                    callback(new Error(this.$t('rules.totalPriceInputError1')));
                                } else {
                                    callback();
                                }
                            } else {
                                callback(new Error(_this.$t('rules.totalPriceInputError2')));
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                monthAmount: [
                    { required: true, message: this.$t('rules.monthAmountInput'), trigger: 'change' },
                    {
                        validator(rule, value, callback) {
                            if (Number.isInteger(Number(value)) && Number(value) > 0) {
                                callback();
                            } else {
                                callback(new Error(_this.$t('rules.monthAmountInputError')));
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                startTime: [
                    { required: true, message: this.$t('rules.startTimePick'), trigger: 'change' }
                ],
                bizType: [
                    { required: true, message: this.$t('rules.bizTypeSelect'), trigger: 'change' }
                ],
                payWays: [
                    { required: true && this.isShowPayType, message: this.$t('rules.payWaysSelect'), trigger: 'change' }
                ],
                payStatus: [
                    { required: true && this.isShowPayStatus, message: this.$t('rules.payStatusSelect'), trigger: 'change' }
                ]
            };

            // 清空表单验证提示信息
            this.$nextTick(function () {
                this.$refs.dataform.clearValidate();
            });

            return baseRules;
        }
    },
    mounted() {
        this.initLoadPage();
    },
    methods: {
        buttonClick() {
            this.$refs.addGoods.doShow();
        },
        initLoadPage() {
            // 加载字典数据
            // 加载发布课程列表
            this.loading = false;
            // 加载组织列表
            this.OrganizationList.length = 0;
            getOrganizationList().then(response => {
                const data = response.data;
                data.forEach(elem => {
                    this.OrganizationList.push({ value: '' + elem.id, label: elem.name });
                });
            });

            getSellerList().then(response => {
                const data = response.data;
                data.forEach(elem => {
                    this.SellerList.push({ value: '' + elem.id, label: elem.name });
                });
            });

            this.$Dictionary.orderType().then(list => {
                this.$convertList(list, this.OrderTypeList, elem => {
                    return elem.code !== '01'; // 过滤个人
                });
            });

            this.$Dictionary.payStatus().then(list => {
                this.$convertList(list, this.PayStatusTypeList, elem => {
                    return elem.code !== '03'; // 过滤取消状态
                });
            });

            this.$Dictionary.payType().then(list => {
                this.$convertList(list, this.PayTypeList, elem => {
                    return true;
                });
            });

            this.$Dictionary.bizType().then(list => {
                this.$convertList(list, this.BizTypeList, elem => {
                    return true;
                });
            });

            // 清空数据
            this.$refs.dataform.resetForm();

            // 清空表单验证提示信息
            this.$nextTick(function () {
                this.$refs.dataform.clearValidate();
            });
        },
        onChange(input) {
            // 判断输入的条目是否已存在List当中,如果存在则直接返回,不做处理
            const list = this.OrganizationList;
            for (const i in list) {
                if (list[i].value === input) {
                    return;
                }
            }

            // 如果需要添加的条目,不存在List当中,则需要提示是否添加条目,并且增加对应的处理
            this.$confirm(this.$t('tip.addOrganizationPrefix') + input + this.$t('tip.addOrganizationSuffix'), this.$t('tip.hint'), {
                confirmButtonText: this.$t('tip.confirm'),
                cancelButtonText: this.$t('tip.cancel'),
                type: 'warning'
            }).then(() => {
                addOrganization({ name: input }).then(response => {
                    this.OrgzList.push(response.data);
                }).catch(() => {
                    this.$messageBox(this.$t('error.addingFailure'));
                });
            }).catch(() => {
                this.formModel.organizationId = '';
                this.$message.info(this.$t('error.cancelled'));
            });
        },
        showPermission(index, row) {
            this.$refs.permissionList.doShow(row.list);
        },
        // 第一个参数 商品对象、 第二个参数 权限对象
        setOrderName(permission, good) {
            if (good) {
                this.formModel.goodsName = good.name;
                this.formModel.price = good.price;
                this.formModel.goodsId = good.id;
                this.permissionVo = permission; // 权限对象
                this.goodsVo = good;
            }
        },
        buildModel() {
            // 如果新增的条目不存在字典当中,则需要在临时字典中取对应的值
            let orgzId = this.formModel.organizationId;
            if (this.OrgzList && this.OrgzList.length) {
                for (var i in this.OrgzList) {
                    if (orgzId === this.OrgzList[i].name) {
                        orgzId = this.OrgzList[i].id;
                        break;
                    }
                }
            }
            return orgzId;
        },
        packageCode() {
            if (this.permissionType == '01') {
                this.createPackage();
            } else if (this.permissionType == '02') {
                this.createPermission();
            }
        },
        createPackage() {
            this.$refs.dataform.validateForm(() => {
                this.orderList = [];
                this.goodsList.forEach(item => {
                    this.formModel.organizationId = this.buildModel();
                    // const param = deepAssign({}, this.formModel);
                    const param = {
                        goodItem: item.goodItem,
                        permissionType: item.permissionType
                    };
                    this.orderList.push(param);
                });
                this.packForm(); // 打包 生成二维码
            });
        },
        packForm() {
            if (this.orderList && this.orderList.length) {
                const arr = this.goodsList.map(nor => {
                    return nor.permissionId;
                });
                const param = {
                    // createVO: {isPackage: false, relPermissions: arr},
                    // orderList: this.orderList,
                    // canDistribute: this.formModel.canDistribute == '01'
                    isPackage: false,
                    organizationId: this.formModel.organizationId,
                    packageNum: this.formModel.amount,
                    amount: this.formModel.amount,
                    monthAmount: this.formModel.monthAmount,
                    packageName: this.goodsVo.name,
                    totalPrice: this.formModel.totalPrice,
                    orderType: this.formModel.orderType,
                    distributeType: this.formModel.canDistribute == '01',
                    startTime: this.formModel.startTime,
                    payStatus: this.formModel.payStatus,
                    bizType: this.formModel.bizType,
                    payWays: this.formModel.payWays,
                    forever: this.formModel.forever,

                    // mapId: this.goodsList[0].mapId,
                    relPermissions: arr,
                    orderDetailList: this.orderList
                };
                createPermission(param).then(res => {
                    this.urlInfo = {
                        url: res.data,
                        title: this.$t('orderAuthor.permissionToDistributeQRCode')
                    };
                    this.$emit('orderNext', this.urlInfo);
                }).catch((error) => {
                    this.$messageBox(`${error.message}`);
                });
            } else {
                this.$messageBox(this.$t('tip.selectPackagingRecord'));
            }
        },
        // 万能权限生成订单，生成二维码
        createPermission() {
            this.$refs.dataform.validateForm(() => {
                this.formModel.organizationId = this.buildModel();
                const param = {
                    // createVO: {
                    //     isPackage: true,
                    //     relPermissions: this.permissionVo.relPermissions,
                    //     name: this.permissionVo.name,
                    //     id: this.permissionVo.id,
                    //     remarks: this.permissionVo.remarks
                    // },
                    // goodsVO: this.goodsVo,
                    // orderList: [this.formModel],
                    // canDistribute: this.formModel.canDistribute == '01'
                    isPackage: true,
                    organizationId: this.formModel.organizationId,
                    packageNum: this.formModel.amount,
                    startTime: this.formModel.startTime,
                    monthAmount: this.formModel.monthAmount,
                    distributeType: this.formModel.canDistribute == '01',
                    bizType: this.formModel.bizType,
                    payWays: this.formModel.payWays,
                    forever: this.formModel.forever,
                    payStatus: this.formModel.payStatus,
                    totalPrice: this.formModel.totalPrice,
                    contractNo: this.formModel.contractNo,
                    orderType: this.formModel.orderType,

                    packageName: this.goodsVo.name,
                    remarks: this.goodsVo.remarks,
                    price: this.goodsVo.price,
                    tryUse: this.goodsVo.tryUse,
                    tryUseTime: this.goodsVo.tryUseTime,
                    tryUseTimeUnit: this.goodsVo.tryUseTimeUnit,
                    relPermissions: this.permissionVo.relPermissions,

                    mapId: this.permissionVo.mapId
                    // prdCode: this.permissionVo.prdCode
                };
                createPermission(param).then(res => {
                    this.urlInfo = {
                        url: res.data,
                        title: this.$t('orderAuthor.permissionToDistributeQRCode')
                    };
                    this.$emit('orderNext', this.urlInfo);
                }).catch(error => {
                    this.$messageBox(`${error.message}`);
                });
            });
        },
        back() {
            this.$emit('back');
        }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
	.pack-rule {
        width: 800px;
        margin: 0 auto;
        margin-top: 12px;
        padding: 40px;
	}
	.draft {
        width: 400px;
        text-align: center;
        margin: 20px auto;
    }
</style>
