<template>
    <div>
        <el-dialog :title="title" v-if="visible" :visible.sync="visible" width="70%" :before-close="cancel" append-to-body
            :close-on-click-modal="false">
            <el-form class="project-form" ref="form" :key="'form_' + form.projectId || 'add'" :model="form"
                :rules="rules" label-position="top">
                <el-row v-if="type === 'edit'">
                    <el-col :span="24">
                      <!--项目步骤进度-->
                      <el-form-item :label="$t('project.progress')" prop="progress">
                        <ProjectProgress v-model="form.progress" />
                      </el-form-item>
                    </el-col>
                  </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <!-- 项目名称 -->
                        <el-form-item :label="$t('project.name')" prop="projectName">
                            <el-input :disabled="disabled" v-model.trim="form.projectName"
                                :placeholder="$t('common.pleaseInput') + $t('project.name')" maxlength="100"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!-- 关联客户 -->
                        <PageSelect :label="$t('project.relatedCustomer')" prop="accountId" @change="changeAccountPage"
                            :disabled="disabled" :list="listRemotePage" :pageSize="10" valueProp="accountId"
                            labelProp="accountNo" idName="accountId" clearable required width="100%"
                            :placeholder="$t('common.pleaseSelect') + $t('project.relatedCustomer')"
                            :defaultParams="{ hasProjectFlag: 'Yes' }" :formatLabel="formatLabel" :visibleGetData="true"
                            class="account-select" :defaultData="defaultData" />
                    </el-col>
                </el-row>
                <!-- 关联线索 -->

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item :label="$t('account.lead')" prop="leadIds">
                      <el-select class="lead-select w-100" :disabled="disabled" v-model="form.leadIds" clearable multiple
                                 collapse-tags :popper-append-to-body="false"
                                 :placeholder="$t('common.pleaseSelect') + $t('account.lead')" >
                        <el-option v-for="item in myLeadList" :key="item.leadId" :label="formatLeadLabel(item)"
                                   :value="item.leadId" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <!-- 标杆项目 -->
                    <el-form-item :label="$t('project.isModel')" prop="modelFlag">
                      <el-select :disabled="disabled"  v-model="form.modelFlag" clearable class="w-100"
                                 :placeholder="$t('common.pleaseSelect') + $t('project.isModel')">
                        <el-option v-for="dict in dict.type.project_flag" :key="dict.value" :label="dict.label"
                                   :value="dict.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>


                <el-row :gutter="20">
                    <el-col :span="12">
                        <!-- 区域 -->
                        <el-form-item :label="$t('user.area')" prop="areaId">
                            <treeselect class="treeselect" v-model="form.areaId" disabled :noResultsText="$t('common.noResultsText')"
                                :options="areaTree" :placeholder="$t('common.pleaseSelect') + $t('project.area')"
                                :show-count="true" :normalizer="normalizer"></treeselect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!-- 国家 -->
                        <el-form-item :label="$t('project.countryId')" prop="countryId">
                            <el-select  v-model="form.countryId" disabled class="w-100"
                                :placeholder="$t('common.pleaseSelect') + $t('project.countryId')">
                                <el-option v-for="item in countryList" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <!-- 城市 -->
                        <el-form-item :label="$t('project.city')" prop="city">
                            <el-input :disabled="disabled" v-model.trim="form.city"
                                :placeholder="$t('common.pleaseInput') + $t('project.city')" maxlength="100"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!-- 项目类型 -->
                        <el-form-item :label="$t('lead.segment')" prop="type">
                            <el-select :disabled="disabled"  v-model="form.type" clearable class="w-100"
                                :placeholder="$t('common.pleaseSelect') + $t('lead.segment')">
                                <el-option v-for="dict in dict.type.project_type" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <!-- 产品系列 -->
                        <el-form-item :label="$t('project.projectSegments')" prop="segmentedMarket">
                            <el-select :disabled="disabled"  v-model="form.segmentedMarket" class="w-100"
                                clearable :placeholder="$t('common.pleaseSelect') + $t('project.projectSegments')">
                                <el-option v-for="dict in dict.type.project_market" :key="dict.value"
                                    :label="dict.label" :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                  <el-col :span="12">
                    <!-- 项目交期 -->
                    <el-form-item :label="$t('project.completionYear')" prop="completionYear">
                      <el-date-picker  :disabled="disabled" v-model="form.completionYear" style="width: 100%;"
                                       type="date" :placeholder="$t('common.pleaseSelect') + $t('project.completionYear')">
                      </el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <!-- 计划成交月份 -->
                        <el-form-item :label="$t('account.planDealMonth')" prop="planDealMonth">
                            <el-date-picker  :disabled="disabled" v-model="form.planDealMonth" style="width: 100%;"
                                type="month" :placeholder="$t('common.pleaseSelect') + $t('account.planDealMonth')">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!-- 项目地址 -->
                        <el-form-item :label="$t('project.address')" prop="address">
                            <el-input :disabled="disabled" v-model.trim="form.address"
                                :placeholder="$t('common.pleaseInput') + $t('project.address')"
                                maxlength="100"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <!-- 关键决策人 -->
                        <el-form-item :label="$t('project.keyContactPerson')" prop="keyContactPerson">
                            <el-input :disabled="disabled" v-model.trim="form.keyContactPerson"
                                :placeholder="$t('common.pleaseInput') + $t('project.keyContactPerson')"
                                maxlength="100"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!-- 关键决策人 职位 -->
                        <el-form-item :label="$t('project.keyJobTitle')" prop="keyJobTitle">
                            <el-input :disabled="disabled" v-model.trim="form.keyJobTitle"
                                :placeholder="$t('common.pleaseInput') + $t('project.keyJobTitle')"
                                maxlength="100"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <!-- 关键决策人 电话 -->
                        <el-form-item :label="$t('project.keyContact')" prop="keyContact">
                            <el-input :disabled="disabled" v-model.trim="form.keyContact"
                                :placeholder="$t('common.pleaseInput') + $t('project.keyContact')"
                                maxlength="100"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!-- 关键决策人 邮箱 -->
                        <el-form-item :label="$t('project.keyEmail')" prop="keyEmail">
                            <el-input :disabled="disabled" v-model.trim="form.keyEmail"
                                :placeholder="$t('common.pleaseInput') + $t('project.keyEmail')"
                                maxlength="100"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <!-- 联系人 -->
                        <el-form-item :label="$t('project.contactPerson')" prop="contactPerson">
                            <el-select :disabled="disabled"  v-model.trim="form.contactPerson" class="w-100"
                                clearable @change="changeContactPerson" :allow-create="true" filterable
                                :placeholder="$t('common.pleaseSelect') + $t('project.contactPerson')">
                                <el-option v-for="item in contactList" :key="item.contactId" :label="item.contactName"
                                    :value="item.contactName" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!-- 职位 -->
                        <el-form-item :label="$t('project.jobTitle')" prop="jobTitle">
                            <el-input :disabled="disabled" v-model.trim="form.jobTitle"
                                :placeholder="$t('common.pleaseInput') + $t('project.jobTitle')"
                                maxlength="100"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <!-- 电话 -->
                        <el-form-item :label="$t('project.contact')" prop="contact">
                            <el-input :disabled="disabled" v-model.trim="form.contact"
                                maxlength="100" minlength="5"
                                :placeholder="$t('common.pleaseInput') + $t('project.contact')"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!-- 邮箱 -->
                        <el-form-item :label="$t('user.email')" prop="email">
                            <el-input :disabled="disabled" v-model.trim="form.email"
                                :placeholder="$t('common.pleaseInput') + $t('user.email')" maxlength="100"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <!-- 负责人 -->
                        <Select :disabled="disabled" prop="owner" :data="ownerList" :label="$t('agent.head')" width="100%"
                            valueProp="userId" labelProp="nickName" required></Select>
                    </el-col>
                    <el-col :span="12">
                      <!-- 代理商 -->
                      <Select disabled prop="ownerAgent" :data="agentList" :label="$t('lead.agent')" width="100%"
                              valueProp="agentId" labelProp="agentName" required></Select>
                    </el-col>
                </el-row>
                <!-- 解决方案 -->
                <el-form-item :label="$t('project.solution')" prop="solution">
                    <el-input :disabled="type === 'view'" v-model.trim="form.solution" type="textarea" style="width: 100%;"
                        :placeholder="$t('common.pleaseInput') + $t('project.solution')" maxlength="250"></el-input>
                </el-form-item>
                <!-- 特殊需求 -->
                <el-form-item :label="$t('project.specialRemark')" prop="specialRemark">
                    <el-input :disabled="type === 'view'" v-model.trim="form.specialRemark" type="textarea"
                        style="width: 100%;" :placeholder="$t('common.pleaseInput') + $t('project.specialRemark')"
                        maxlength="250"></el-input>
                </el-form-item>
                <!-- 备注 -->
                <el-form-item :label="$t('common.remark')">
                    <el-input :disabled="type == 'view'" v-model="form.remark" type="textarea" style="width: 100%;"
                        maxlength="500" show-word-limit
                        :placeholder="$t('common.pleaseInput') + $t('common.remark')"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button v-if="type != 'view'" type="primary" icon="el-icon-circle-check" @click="submitForm"
                    :loading="submitLoading">{{ $t('common.confirm') }}</el-button>
                <el-button @click="cancel" icon="el-icon-remove-outline">{{ $t('common.cancel') }}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { addProject, updateProject } from "@/api/business/crm/project";
import { getAreaTree } from "@/api/common/common";
import { getAllNationList } from "@/api/user/country";
import { listRemotePage } from "@/api/business/crm/account";
import { listLead } from "@/api/business/crm/lead";
import { getRelatedContact } from "@/api/business/crm/contact";
import { getOwnerList } from "@/api/system/user";
import { selectByOwner } from "@/api/user/agent";
import PageSelect from "../../../components/element/form/items/PageSelect";
import CommonSelect from "../../../components/element/form/items/CommonSelect";
import { selectLeadListByAccount } from "@/api/business/crm/lead";
import ProjectProgress from '@/views/crmManagement/project/ProjectProgress.vue'

export default {
    name: "ProjectDialog",
    dicts: ['project_flag', 'project_market', 'project_type', 'project_status', 'currency_type'],
    components: { ProjectProgress, CommonSelect, PageSelect, Treeselect },
    props: {
        visible: {
            type: Boolean,
            default: false,
        },
        title: {
            type: String,
            default: "",
        },
        form: {
            type: Object,
            default: () => { },
        },
        type: {
            type: String,
            default: "add",
        },
    },
    data() {
        return {
            rules: {
                projectName: [
                    { required: true, message: this.$t('common.pleaseInput') + this.$t('project.name'), trigger: 'blur' },
                ],
                modelFlag: [
                    { required: true, message: this.$t('common.pleaseSelect') + this.$t('project.isModel'), trigger: 'change' },
                ],
                countryId: [
                    { required: true, message: this.$t('common.pleaseSelect') + this.$t('project.countryId'), trigger: 'change' },
                ],
                areaId: [
                    { required: true, message: this.$t('common.pleaseSelect') + this.$t('project.area'), trigger: 'change' },
                ],
                type: [
                    { required: true, message: this.$t('common.pleaseSelect') + this.$t('lead.segment'), trigger: 'change' },
                ],
                segmentedMarket: [
                    { required: true, message: this.$t('common.pleaseSelect') + this.$t('project.projectSegments'), trigger: 'change' },
                ],
                city: [
                    { required: true, message: this.$t('common.pleaseInput') + this.$t('project.city'), trigger: 'blur' },
                ],
                // planDealMonth: [
                //     { required: true, message: this.$t('common.pleaseSelect') + this.$t('account.planDealMonth'), trigger: 'change' },
                // ],
                // contactPerson: [
                //     { required: true, message: this.$t('common.pleaseSelect') + this.$t('project.contactPerson'), trigger: 'change' },
                // ],
                // contact: [
                //     { required: true, message: this.$t('common.pleaseInput') + this.$t('project.contact'), trigger: 'blur' },
                // ],
                // email: [
                //     { required: true, message: this.$t('common.pleaseInput') + this.$t('project.address'), trigger: 'blur' },
                // ],
                keyContactPerson: [
                    { required: true, message: this.$t('common.pleaseInput') + this.$t('project.keyContactPerson'), trigger: 'blur' },
                ],
                keyContact: [
                    { required: true, message: this.$t('common.pleaseInput') + this.$t('project.keyContact'), trigger: 'blur' },
                ],
                keyEmail: [
                    { required: true, message: this.$t('common.pleaseInput') + this.$t('project.keyEmail'), trigger: 'blur' },
                ],
            },
            accountList: [],
            accounts: [],
            leadList: [],
            countryList: [],
            areaTree: [],
            contactList: [],
            ownerList: [],
            language: null,
            submitLoading: false,
            accountLoading: false,
            userInfo: {},
            agentList: [],
            myLeadList: [],
            defaultData: [],

          // progressActive: 0,
        }
    },
    created() {
        this.language = this.$i18n.locale;
        this.userInfo = this.$store.state.user.userInfo;
        this.initData();
    },
    computed: {
        disabled: function () {
            return this.type == 'edit' && (this.form.status != '01' && this.form.status != '02')
        },
    },

    watch: {
      visible: function(val) {
        if (val) {
          this.$refs.form && this.$refs.form.clearValidate();
          this.getPageLeadListByAccount()
        }
      }
    },

    methods: {
        listRemotePage,
        formatLeadLabel(item) {
            return item.leadNo
                + ': 【' + (item.areaName || '') + '】'
                + ' 【' + (item.company || '') + '】'
                + ' 【' + (item.contactPerson || '') + '】'
            // + ' 【' + (this.formatDict(item.sector, this.dict.type.lead_industry) || '') + '】'
        },
        formatLabel(accountNo, item) {
            return item.accountNo + ": 【" + item.accountName + "】"
        },
        getAgentListByOwner() {
            return selectByOwner(this.$store.getters.userId).then(res => {
                this.agentList = res.data;
            })
        },
        initData() {
            Promise.all([
                this.getCountryList(),
                this.getAreaTree(),
                this.getOwnerList(),
                this.getAgentListByOwner(),
            ]).then(([countryList, agentTree, ownerList]) => {
                this.countryList = countryList.map(item => {
                    let label = '';
                    switch (this.language) {
                        case 'chinese':
                            label = item.countryName
                            break;
                        case 'english':
                            label = item.countryNameUS
                            break;
                        case 'russia':
                            label = item.countryNameRU
                            break;
                        case 'spanish':
                            label = item.countryNameES
                            break;
                    }
                    return {
                        value: item.countryId,
                        label: label
                    }
                });
                this.areaTree = agentTree;
                this.ownerList = ownerList;
            });
        },
        normalizer(node) {
            switch (this.language) {
                case 'chinese':
                    return {
                        label: node.label,
                    };
                case 'english':
                    return {
                        label: node.labelES,
                    };
                case 'russia':
                    return {
                        label: node.labelRU,
                    };
                case 'spanish':
                    return {
                        label: node.labelUS,
                    };
            }
        },
        /** 查询客户所有人列表 */
        getOwnerList() {
            return getOwnerList({onlySalesRole: true}).then(response => {
                return response.data;
            })
        },
        /** 获取字典数据匹配的值 */
        formatDict(value, dictData) {
            return dictData.find(dict => dict.value == value)?.label;
        },
        /** 获取地区树 */
        getAreaTree() {
            return getAreaTree().then(response => {
                return response.data;
            });
        },
        /** 查询国家列表 */
        getCountryList() {
            return getAllNationList().then(response => {
                return response.data;
            })
        },
        /** 查询线索列表 */
        getLeadList() {
            return listLead().then(response => {
                return response.rows;
            })
        },
        /** 查询联系人列表 */
        getRelatedContact(accountId) {
            getRelatedContact({ accountId: accountId }).then(response => {
                this.contactList = response.rows;
            })
        },
        changeAccountPage(row) {
            console.log("12312312312")
            this.$set(this.form, 'contactPerson', null);
            this.$set(this.form, 'contact', null);
            this.$set(this.form, 'leadIds', null);
            this.contactList = [];
            this.myLeadList = [];
            if (this.form.accountId) {
                let account = row
                this.$set(this.form, 'countryId', account.countryId);
                this.$set(this.form, 'areaId', account.areaId);
                // this.$set(this.form, 'owner', account.owner);
                this.$set(this.form, 'ownerAgent', account.ownerAgent);
                this.getRelatedContact(this.form.accountId);

                this.getPageLeadListByAccount();
            } else {
                this.$set(this.form, 'areaId', null);
                this.$set(this.form, 'countryId', null);
                // this.$set(this.form, 'owner', null);
            }
        },

        getPageLeadListByAccount() {
          let param = {
            pageNum: 1,
            pageSize: 0,
            relativeAccount: this.form.accountId
          }

          // console.log('param::::::::', param)
          return selectLeadListByAccount(param).then(response => {
            this.myLeadList = response.rows;
          });
        },

        changeContactPerson() {
            this.$set(this.form, 'contact', null);
            if (this.form.contactPerson) {
                let contact = this.contactList.find(item => item.contactName == this.form.contactPerson)
                if (contact) {
                    this.$set(this.form, 'contact', contact.phone);
                }
            }
        },
        cancel() {
            this.contactList = [];
            this.accountList = [];
            this.defaultData = [];
            // 清除表单验证
            this.$refs["form"].clearValidate();
            this.$emit('closeDialog', false);
        },
        cancelBack() {
            this.contactList = [];
            this.accountList = [];
            this.defaultData = [];
            this.$emit('closeDialog', true);
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.submitLoading = true;
                    if (this.form.projectId != undefined) {
                        updateProject(this.form).then(response => {
                            if (response.code == 200) {
                                this.$modal.msgSuccess(this.$t('common.editSuccess'));
                                this.cancelBack();
                            } else {
                                this.$modal.msgError(response.msg);
                            }
                            this.submitLoading = false;
                        }).catch(() => { this.submitLoading = false; });
                    } else {
                        addProject(this.form).then(response => {
                            if (response.code == 200) {
                                this.$modal.msgSuccess(this.$t('common.addSuccess'));
                                this.cancelBack();
                            } else {
                                this.$modal.msgError(response.msg);
                            }
                            this.submitLoading = false;
                        }).catch(() => { this.submitLoading = false; });
                    }
                }
            });
        },

    }
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
// ::v-deep .completion-year el-date-editor{
//     width: 350px;
// }


::v-deep .treeselect {
    .vue-treeselect__single-value {
        color: #C0C4CC;
    }

    .vue-treeselect__control {
        border-color: #E4E7ED;
        background-color: #F5F7FA;
    }
}

.project-form {
    padding: 0 20px;
}

::v-deep .project-form .el-form-item--medium .el-form-item__label {
    line-height: 10px;
}


</style>
