<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 :key="'form_' + form.projectId || 'add'" ref="form" :model="form" :rules="rules"
               class="project-form" label-position="top"
      >
        <!--<el-row v-if="type === 'edit'">-->
        <!--    <el-col :span="24">-->
        <!--      &lt;!&ndash;项目步骤进度&ndash;&gt;-->
        <!--      <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 v-model="form.projectName" :disabled="specialDis"
                        :placeholder="$t('common.pleaseInput') + $t('project.name')" maxlength="100"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 关联客户 -->
            <PageSelect :defaultData="defaultData" :defaultParams="{ hasProjectFlag: 'Yes' }" :disabled="disabled"
                        :formatLabel="formatLabel" :label="$t('project.relatedCustomer')" :list="listRemotePage" :pageSize="10"
                        :placeholder="$t('common.pleaseSelect') + $t('project.relatedCustomer')" :visibleGetData="true" class="account-select" clearable idName="accountId"
                        labelProp="accountNo"
                        prop="accountId" required valueProp="accountId"
                        width="100%" @change="changeAccountPage"
            />
          </el-col>
        </el-row>


        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 代理商 -->
            <Select :data="agentList" :label="$t('lead.agent')"  labelProp="agentName" prop="ownerAgent"
                    required valueProp="agentId" width="100%" :disabled="specialDis"
            ></Select>
          </el-col>
          <!-- 项目进度 dict.type.project_progress -->
          <el-col :span="12">
            <Input :label="$t('project.progress')" disabled prop="progress" width="100%" />
          </el-col>
        </el-row>


        <el-row :gutter="20">
          <!--项目状态-->
          <el-col :span="12">
            <Select :data="projectProgress" :label="$t('project.status')" prop="progress"
                     width="100%" @change="progressChange"
            />
          </el-col>
          <!-- 标杆项目 -->
          <el-col :span="12">
            <el-form-item :label="$t('project.isModel')" prop="modelFlag">
              <el-select v-model="form.modelFlag" :disabled="specialDis" :placeholder="$t('common.pleaseSelect') + $t('project.isModel')" class="w-100"
                         clearable
              >
                <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('lead.segment')" prop="type">
              <el-select v-model="form.type" :disabled="specialDis" :placeholder="$t('common.pleaseSelect') + $t('lead.segment')" class="w-100"
                         clearable
              >
                <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-col :span="12">
            <!-- 产品细分市场 -->
            <el-form-item :label="$t('project.projectSegments')" prop="segmentedMarket">
              <el-select v-model="form.segmentedMarket" :disabled="specialDis" :placeholder="$t('common.pleaseSelect') + $t('project.projectSegments')"
                         class="w-100" clearable
              >
                <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-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 区域 -->
            <el-form-item :label="$t('user.area')" prop="areaId">
              <treeselect v-model="form.areaId" :noResultsText="$t('common.noResultsText')" :normalizer="normalizer"
                          :options="areaTree"
                          :placeholder="$t('common.pleaseSelect') + $t('project.area')" :show-count="true"
                          class="treeselect" disabled
              ></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" :placeholder="$t('common.pleaseSelect') + $t('project.countryId')" class="w-100"
                         disabled
              >
                <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 v-model="form.city"  :disabled="specialDis"
                        :placeholder="$t('common.pleaseInput') + $t('project.city')" maxlength="30"
              ></el-input>
            </el-form-item>
          </el-col>

          <!--币种种类-->
          <el-col :span="12">
            <Select :data="dict.type.currency_type"
                    :label="$t('project.currency')" prop="currencyId" required width="100%"
            />
          </el-col>

        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-table  :data="form.machineList" :header-cell-style="{ background: '#F4F6F8', color: '#92A2B5' }"
                      show-summary :summary-method="getSummaries" :span-method="arraySpanMethod" ref="tableRef"
                      border style="margin-bottom: 15px;"
            >

              <!--规格-->
              <el-table-column prop="standard" width="300" align="center" >
                <template slot="header" slot-scope="scope">
                  <el-tooltip class="item" effect="dark" placement="top">
                    <div slot="content">TWJ630/1.0-7/7/7 or KYS235-1000-3500</div>
                    <div style="">
                      <span>{{$t('project.standard')}}</span>
                      <i class="el-icon-info"></i>
                    </div>
                  </el-tooltip>
                </template>
                <template slot-scope="{row}">
                  <el-input v-model="row.standard" style="width: 100%;" maxlength="100"
                            @blur="row.standard = $event.target.value.trim()" clearable/>
                </template>
              </el-table-column>

              <!-- 梯型 -->
              <el-table-column prop="elevatorModel" :label="$t('project.elevatorModel')" width="200" align="center">
                <template slot="header" slot-scope="scope">
                  <el-tooltip class="item" effect="dark" placement="top">
                    <div slot="content">KW2600 or KYS</div>
                    <div>
                      <span>{{$t('project.elevatorModel')}}</span>
                      <i class="el-icon-info"></i>
                    </div>
                  </el-tooltip>
                </template>

                <template slot-scope="{row}">
                  <el-input v-model="row.elevatorModel" style="width: 100%;" maxlength="30"
                            @blur="row.elevatorModel = $event.target.value.trim()" clearable/>
                </template>
              </el-table-column>

              <!--设备类型-->
              <Column :label="$t('project.equipmentType')" prop="equipmentType">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.equipmentType" :disabled="type === 'view'" :placeholder="$t('common.pleaseSelect')" clearable
                             filterable
                  >
                    <el-option v-for="dicts in dict.type.intentional_product" :key="dicts.value"
                               :label="dicts.label" :value="dicts.value"
                    />
                  </el-select>
                </template>
              </Column>

              <!--金额-->
              <Column :label="$t('quotation.unitPriceLabel')" prop="amount">
                <template slot-scope="scope">
                  <!--                      <el-input-number v-model="scope.row.amount" :controls="false" :disabled="type === 'view'"-->
                  <!--                                       :max="99999999.99" :precision="2" style="width: 100%;"-->
                  <!--                      />-->
                  <MoneyInput :inputValue="scope.row.amount" :zeroLength="2" @change="item=>valueChanged(item,scope.row)" :style="{color:scope.row.amount > 99999999.99 ?'red':'green'}"></MoneyInput>
                </template>
              </Column>

              <!--个数-->
              <Column :label="$t('project.equipmentQuantity')" prop="equipmentQuantity">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.equipmentQuantity" :controls="false"
                                   :disabled="type === 'view'"
                                   :max="99999999" style="width: 100%;"
                  />
                </template>
              </Column>
              <!--合计-->
              <Column :label="$t('project.priceTotal')" prop="" align="right">
                <template slot-scope="{row}">
                        <span >
                          {{ toDecimal2(numFormat(totalPrice(row))) }}
                        </span>
                </template>
              </Column>
              <!--操作-->
              <el-table-column :label="$t('common.operate')" align="center" fixed="right" width="150">
                <template slot="header" slot-scope="scope">
                  <div>
                    <span>{{ $t('common.operate') }}</span>
                    <!--新增行-->
                    <el-button icon="el-icon-plus" plain size="mini" style="margin-left: 10px;" type="primary"
                               @click="addMachine"
                    ><!--添加行--></el-button>
                  </div>
                </template>

                <template slot-scope="scope">
                  <el-button v-if="type != 'view'" icon="el-icon-delete" type="text"
                             @click="delMachine(scope.$index)"
                  >{{ $t('common.delete') }}
                  </el-button>
                </template>

              </el-table-column>
            </el-table>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 关键决策人 -->
            <el-form-item :label="$t('project.keyContactPerson')" prop="keyContactPerson">
              <el-input v-model="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 v-model="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 v-model="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 v-model="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('account.planDealMonth')" prop="planDealMonth">
              <el-date-picker v-model="form.planDealMonth" :placeholder="$t('common.pleaseSelect') + $t('account.planDealMonth')"
                              style="width: 100%;" type="date"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <!--预期安装开始日期-->
            <DatePicker :label="$t('project.expectedInstallStartDate')" prop="expectedInstallStartDate"
                        width="100%" type="date"/>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <!-- 联系人 -->
            <el-form-item :label="$t('project.contactPerson')" prop="contactPerson">
              <el-select v-model="form.contactPerson" :allow-create="true"
                         :placeholder="$t('common.pleaseSelect') + $t('project.contactPerson')" class="w-100" clearable filterable
                         @change="changeContactPerson"
              >
                <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 v-model="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 v-model="form.contact"
                        :placeholder="$t('common.pleaseInput') + $t('project.contact')" maxlength="100"
                        minlength="5"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 邮箱 -->
            <el-form-item :label="$t('user.email')" prop="email">
              <el-input v-model="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 :data="ownerList" :disabled="disabled" :label="$t('agent.head')" labelProp="nickName" prop="owner"
                    required valueProp="userId" width="100%"
            ></Select>
          </el-col>

          <!-- 关联线索 -->
          <el-col :span="12">
            <el-form-item :label="$t('account.lead')" prop="leadIds">
              <el-select v-model="form.leadIds" :disabled="disabled" :placeholder="$t('common.pleaseSelect') + $t('account.lead')" :popper-append-to-body="false" class="lead-select w-100"
                         clearable collapse-tags
                         multiple
              >
                <el-option v-for="item in myLeadList" :key="item.leadId" :label="formatLeadLabel(item)"
                           :value="item.leadId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <!-- 项目地址 -->
            <el-form-item :label="$t('project.address')" prop="address">
              <el-input v-model="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="24">
            <!-- 特殊需求 -->
            <Input type="textarea" maxlength="255" :disabled="type === 'view'" :label="$t('project.specialRemark')" prop="specialRemark" width="100%"/>
          </el-col>
          <!--<el-col :span="8">-->
          <!--  &lt;!&ndash; 审批状态 &ndash;&gt;-->
          <!--  <Select :data="dict.type.project_status" :disabled="type === 'view'" :label="$t('project.approveStatus')" prop="status"-->
          <!--          required width="100%"/>-->
          <!--</el-col>-->

        </el-row>
        <!--<el-row :gutter="20">-->
        <!--  <el-col :span="12">-->
        <!--    &lt;!&ndash; 项目交期 &ndash;&gt;-->
        <!--    <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-form-item :label="$t('project.solution')" prop="solution">
          <el-input v-model="form.solution" :disabled="type === 'view'" :placeholder="$t('common.pleaseInput') + $t('project.solution')" maxlength="255"
                    style="width: 100%;" type="textarea"
          ></el-input>
        </el-form-item>

        <!-- 备注 -->
        <el-form-item :label="$t('common.remark')">
          <el-input v-model="form.remark" :disabled="type == 'view'" :placeholder="$t('common.pleaseInput') + $t('common.remark')" maxlength="500"
                    show-word-limit style="width: 100%;"
                    type="textarea"
          ></el-input>
        </el-form-item>
        <el-row  v-if="form.progress == '0%' || form.progress == '0% '"  :gutter="20">
          <el-col :span="12">
            <!--原因分类-->
            <Select :label="$t('project.reasonType')" prop="reasonType"
                    :data="dict.type.project_reason_type"/>
          </el-col>
          <el-col :span="12">
            <!-- 竞争对手-->
            <el-form-item :label="$t('project.competitor')" prop="competitor">
              <el-input v-model="form.competitor"
                        :placeholder="$t('common.pleaseInput') + $t('user.competitor')" maxlength="100"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-form-item v-if="form.progress == '0%'" :label="$t('project.delayLoseRemark')" prop="delayRemark">
            <el-input v-model="form.delayRemark" type="textarea" maxlength="250" show-word-limit :rows="4"
                      :placeholder="$t('common.pleaseInput') + $t('project.delayLoseRemark')"></el-input>
          </el-form-item>
          <el-form-item v-if="form.progress == '0% '" :label="$t('project.delayLoseRemark')" prop="loseRemark">
            <el-input v-model="form.loseRemark" type="textarea" maxlength="250" show-word-limit :rows="4"
                      :placeholder="$t('common.pleaseInput') + $t('project.delayLoseRemark')"></el-input>
          </el-form-item>
        </el-row>



      </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 {getAllOwnerList, 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'
import {trimFormFields} from '@/utils/ruoyi'
import InputNumber from '@/components/element/form/items/InputNumber.vue'
import Column from '@/components/element/table/Column.vue'
import MoneyInput from '../../../components/element/form/items/moneyInput'
import {getInputValue, delInput, delcommafy} from "../../../utils/money";
import log from '@/views/monitor/job/log.vue'
import DatePicker from '@/components/element/form/items/DatePicker.vue'


function isNumberOrLocalizedNumber(val) {
    // 正则表达式匹配数字或本地化的数字字符串
    const regex = /^\s*-?\d+(\.\d+)?\s*$|^\s*-?\d{1,3}(,\d{3})*(\.\d+)?\s*$/;
    return val && typeof val === 'string' &&regex.test(val);
}
function deepEqual(obj1, obj2) {
  if (!obj1) {
    obj1 = null
  }
  if (!obj2) {
    obj2 = null
  }
  if (obj1 === obj2) return true;

  if (typeof obj1 !== 'object' || obj1 === null || typeof obj2 !== 'object' || obj2 === null) {
    return false;
  }

  let keys1 = Object.keys(obj1);
  let keys2 = Object.keys(obj2);

  if (keys1.length !== keys2.length) return false;

  for (let key of keys1) {
    let val1 = obj1[key];
    let val2 = obj2[key];
    if (isNumberOrLocalizedNumber(val1)) {
      val1 = parseFloat(val1.replace(/,/g, ''))
    }
    if (isNumberOrLocalizedNumber(val2)) {
      val2 = parseFloat(val2.replace(/,/g, ''))
    }
    if (!keys2.includes(key) || !deepEqual(val1, val2)) {
      console.log("not equal: " + key, val1, val2)
      return false;
    }
  }

  return true;
}


export default {
  name: "ProjectDialog",
  dicts: ['project_flag', 'project_market', 'project_type', 'project_status', 'currency_type', 'intentional_product', 'project_progress', 'elevator_type','project_reason_type'],
  components: { DatePicker, MoneyInput, Column, InputNumber, 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'},
        ],
        city: [
          {required: true, message: this.$t('common.pleaseSelect') + this.$t('project.city'), 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('user.email'), 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: [],
      oldForm: {},
      // progressActive: 0,
    }
  },
  created() {
    this.language = this.$i18n.locale;
    this.userInfo = this.$store.state.user.userInfo;
    this.initData();
  },
  computed: {
    log() {
      return log
    },
    disabled: function () {
      return this.type == 'edit' && (this.form.status != '01' && this.form.status != '02')
    },
    specialDis: function () {
      console.log(this.$store.getters.roles)
      return this.type == 'edit' && (
        (this.form.status != '01' && this.form.status != '02')
        && !this.$store.getters.roles.includes('admin')
        && !this.$store.getters.roles.includes('sales_director')
        && !this.$store.getters.roles.includes('area_sales_director')
      )
    },
    projectProgress() {
      if(this.form.progress && (this.form.progress == '0%' || this.form.progress == '0% ')){
        return this.dict.type.project_progress
      }
      // 过滤掉 '0%' 和 '0% '
      return this.dict.type.project_progress.filter(item => item.value !== '0%' && item.value !== '0% ')
    }
  },

  watch: {
    visible: function (val) {
      if (val) {
        this.$refs.form && this.$refs.form.clearValidate();
        this.getPageLeadListByAccount()
        this.oldForm = JSON.parse(JSON.stringify(this.form))
      }
    },
    // 这里使用监听是不是太重了。
    form: {
      handler: function (val) {
        if (val.accountId) {
          if (!this.form.equipmentQuantity) {
            this.$set(this.form, 'equipmentQuantity', undefined);
          }
          if (!this.form.amount) {
            this.$set(this.form, 'amount', undefined);
          }
        }
        if (!val.machineList) {
          this.$set(this.form, 'machineList', [])
        }
      },
      deep: true
    }
  },

  methods: {
    valueChanged(value, rowAmount) {
      this.$nextTick(() => {
        this.$set(rowAmount,'amount',value)
      })
    },
    delMachine(index) {
      this.form.machineList.splice(index, 1)
    },
    addMachine() {
      let param = {
        standard: "",
        elevatorModel: "",
        equipmentQuantity: 0,
        equipmentType: "",
        amount: 0.00,
        projectId: this.form.projectId
      }
      this.form.machineList.push(param)
    },
    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;

        // this.addMachine()
      });
    },
    normalizer(node) {
      switch (this.language) {
        case 'chinese':
          return {
            label: node.label,
          };
        case 'english':
          return {
            label: node.labelUS,
          };
        case 'russia':
          return {
            label: node.labelRU,
          };
        case 'spanish':
          return {
            label: node.labelES,
          };
      }
    },
    /** 查询客户所有人列表 */
    getOwnerList() {

      if (this.$store.getters.roles.includes('sales_director')) {
        return getAllOwnerList({onlySalesRole: true}).then(res => {
          return res.data;
        })
      } else {
        return getOwnerList({onlySalesRole: true}).then(res => {
          return res.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) {
      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);
          this.$set(this.form, 'email', contact.email);
        }
      }
    },
    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 () {
      trimFormFields(this.form, ['projectName', 'city', 'address', 'keyContactPerson', 'keyJobTitle', 'keyContact', 'keyEmail', 'contact', 'email', 'contactPerson', 'jobTitle', 'contact', 'email', 'solution', 'specialRemark', 'remark'])
      this.$refs["form"].validate(valid => {
        if (valid) {
          try {
            this.checkMachineList()
          } catch (e) {
            return
          }
          let amountFlag = false
          //处理千分位
          this.form.machineList.some(item => {
            if(item.amount > 99999999.99){
              amountFlag = true
              return
            }
            item.amount = delcommafy(item.amount);
          })
          //设备总价校验
          if(amountFlag){
            this.$message.warning(this.$t('project.priceOfTheEquipmentExceedsTheRange'))
            return;
          }
          this.submitLoading = true;
          if (this.form.projectId != undefined) {
            if (deepEqual(this.oldForm, this.form)) {
              this.$modal.msgSuccess(this.$t('common.editSuccess'));
                this.submitLoading = false
                this.cancelBack();
                return
            }
            this.$prompt(this.$t('project.modifyRemarkNote'), this.$t('common.tips'), {
              confirmButtonText: this.$t('common.confirm'),
              cancelButtonText: this.$t('common.cancel'),
              confirmButtonClass: "el-icon-circle-check",
              cancelButtonClass: "el-icon-remove-outline",
              inputPattern: /^\s*\S.{1,500}$/,
              inputErrorMessage: this.$t('project.modifyRemarkNotEmpty')
            }).then(({ value }) => {
              this.form.modifyRemark = value;
              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;
              });
            }).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;
            });
          }
        }
      });
    },

    progressChange(e, o) {
      console.log('progressChange', e, o)
      // 查看页面修改需要弹框警告
      if (this.type === 'view') {
        this.$modal.confirm(this.$t('project.progressUpdateConfirm'))
      }
    },

    totalPrice(row) {
      // 数字 NaN
      let amount = (Number(delcommafy(row.amount)) * Number(row.equipmentQuantity)).toFixed(2) || 0.00
      return amount
    },

    checkMachineList() {
      // 检查 项目设备规格信息是否存在
      if (this.form.machineList.length === 0) {
        return
        // this.$modal.msgError('请添加项目设备信息');
        this.$modal.msgError(this.$t('project.equipmentSpecifications') + this.$t('common.notEmpty'))
        throw new Error('请添加项目设备信息');
      }
      for (const equipment of this.form.machineList) {
        // 规格不能为空
        if (!equipment.standard) {
          this.$modal.msgError(this.$t('project.standard') + this.$t('common.notEmpty'))
          throw new Error('规格不能为空');
        }
        // 梯型不能为空
        if (!equipment.elevatorModel) {
          this.$modal.msgError(this.$t('project.elevatorModel') + this.$t('common.notEmpty'))
          throw new Error('梯型不能为空');
        }
        // 设备类型不能为空
        if (!equipment.equipmentType) {
          this.$modal.msgError(this.$t('project.equipmentType') + this.$t('common.notEmpty'))
          throw new Error('设备类型不能为空');
        }
        if (!equipment.equipmentQuantity) {
          this.$modal.msgError(this.$t('project.equipmentQuantity') + this.$t('common.notEmpty'))
          throw new Error('设备数量不能为空');
        }
        if (equipment.equipmentQuantity <= 0) {
          this.$modal.msgError(this.$t('project.equipmentQuantity') + this.$t('common.cannotBeLe') + '0')
          throw new Error('设备数量不能小于等于0');
        }
        if (!equipment.amount) {
          this.$modal.msgError(this.$t('quotation.unitPriceLabel') + this.$t('common.notEmpty'))
          throw new Error('金额不能为空');
        }
        if (equipment.amount <= 0) {
          this.$modal.msgError(this.$t('quotation.unitPriceLabel') + this.$t('common.cannotBeLe') + '0')
          throw new Error('金额不能小于等于0');
        }
      }
    },

    getSummaries(param) {
      const {columns, data} = param;

      // console.log('columns:', columns)
      // console.log('data:', data)
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = this.$t('common.total');
          return;
        }
        // if (index === 3) {
        //   let total = 0;
        //   for (let i = 0; i < data.length; i++) {
        //     total += Number(data[i].amount);
        //   }
        //   sums[index] = total.toFixed(2);
        //   return;
        // }
        if (index === 4) {
          let total = 0;
          for (let i = 0; i < data.length; i++) {
            total += Number(data[i].equipmentQuantity);
          }
          sums[index] = total;
          return;
        }
        if (index === 5) {
          let total = 0;
          for (let i = 0; i < data.length; i++) {
            total += Number(delcommafy(data[i].amount)) * Number(data[i].equipmentQuantity);
          }
          // sums[index] = total.toFixed(2)
          sums[index] = this.toDecimal2(this.numFormat(total.toFixed(2)))
          return;
        }
        sums[index] = '';
      });

      return sums;
    },

    arraySpanMethod({row, column, rowIndex, columnIndex}) {
      this.$nextTick(() => {
        if (this.$refs.tableRef.$el) {
          let current = this.$refs.tableRef.$el
            .querySelector(".el-table__footer-wrapper")
            .querySelector(".el-table__footer");
          let cell = current.rows[0].cells;
          for (let i = 1; i < 4; i++) {
            cell[i].style.display = "none";
          }
          cell[0].colSpan = "4"; // 合并单元格
          cell[0].style.textAlign = 'left'
          // cell[4].style.textAlign = 'right'
        }
      });
    },
  }
}
</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: 16px;
}


</style>
