<template>
  <div class="app-container" v-loading="fullLoading">
    <!--<card-table :modalData="projectList" labelWidth="120px" :searchParams="queryParams" @pagination="getList"-->
    <!--            :loading="loading" :tableSearch="true" @columnSearch="handleQuery" @resetList="resetQuery" :max-height="tableMaxHeight"-->
    <!--            row-key="rowKey" @selection-change="handleSelectionChange" @sortChange="sortChange">-->
    <card-table :modalData="projectList" labelWidth="120px" :searchParams="queryParams" @pagination="getList" show-selection
                :loading="loading" :tableSearch="true" @columnSearch="handleQuery" @resetList="resetQuery" :max-height="tableMaxHeight"
                row-key="rowKey" :cell-class-name="isChildRow" @selection-change="handleSelectionChange" @sortChange="sortChange">
      <template #operations="{ selections }">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                     v-hasPermi="['business:project:add']">{{ $t('project.addProject') }}
          </el-button>
        </el-col>
        <el-col :span="1.5" style="margin-left: 10px;">
          <ImportModal v-hasPermi="['business:project:import']" :close="getList" :tableType="10"
                       :title="$t('common.import')"
                       icon="el-icon-upload2" style="margin: 0 10px;"
          ></ImportModal>
        </el-col>
        <el-col :span="1.5" style="margin-left: 10px;">
          <el-button plain icon="el-icon-download" size="mini" @click="handleExport"
                     v-hasPermi="['business:project:export']">{{ $t('common.export') }}
          </el-button>
        </el-col>
      </template>
      <template #default="{ list }">
        <!--<el-table-column type="selection" width="50" align="center" />-->
        <!--<el-table-column label="No." type="index" width="50" align="center" fixed />-->
        <el-table-column type="index" label="No." width="50" align="center" fixed>
          <template slot-scope="scope">
            <span>{{ scope.row.index }}</span>
          </template>
        </el-table-column>
        <!-- 项目编码 -->
        <Column :label="$t('project.no')" prop="projectNo" :searchParams="queryParams" :showSearch="true" fixed
                sortable="custom" width="200">
          <template #default="{ row }">
            <span @click="handleView(row)" class="link-type">{{ row.projectNo }}</span>
          </template>
        </Column>
        <!-- 项目名称 -->
        <Column :label="$t('project.name')" prop="projectName" :searchParams="queryParams" :showSearch="true" fixed
                width="250px"/>
        <!-- 区域 -->
        <Column v-if="showAreaColumn" :label="$t('user.area')" prop="areaId" :searchParams="queryParams"
                :searchDict="areaList" :showSearch="true" valueProp="first" labelProp="second"
                searchType="select" selectMore width="200px"/>
        <!-- 国家 -->
        <Column :label="$t('account.country')" prop="countryId" :searchParams="queryParams" :showSearch="true"
                valueProp="first" labelProp="second" searchType="select"
                :searchDict="countryList" select-more width="200px"/>
        <!-- 城市 -->
        <Column :label="$t('project.city')" prop="city" :searchParams="queryParams" :showSearch="true" width="200px"/>



        <!--所属代理商-->
        <Column :label="$t('lead.agent')" prop="ownerAgent" :showSearch="true" search-type="select"
                :searchParams="queryParams" :search-dict="agentList" select-more value-prop="agentId"
                label-prop="agentName"
                width="250px">
          <template #default="{ row }">
            <span>{{
                row.ownerAgentName == 'common.head' ? $t(row.ownerAgentName) :
                  row.ownerAgentName
              }}</span>
          </template>
        </Column>


        <!--&lt;!&ndash;设备数量&ndash;&gt;-->
        <!--<Column :label="$t('project.equipmentQuantity')" prop="equipmentQuantity" />-->
        <!--&lt;!&ndash;设备类型&ndash;&gt;-->
        <!--<Column :label="$t('project.equipmentType')" prop="equipmentType" />-->
        <!--&lt;!&ndash;金额&ndash;&gt;-->
        <!--<Column :label="$t('project.amount')" prop="amount" />-->


        <!--设备总数-->
        <Column :label="$t('project.deviceTotal')" prop="deviceTotal" />

        <!--币种-->
        <Column :label="$t('project.currency')" prop="currencyId"
                searchType="select" :searchDict="dict.type.currency_type"/>

        <!--总价-->
        <Column :label="$t('project.priceTotal')" prop="priceTotal" align="right">
          <template #default="{ row }">
            <!--保留两位小数-->
            <span>{{ row.priceTotalStr }}</span>
          </template>
        </Column>

        <!-- 项目状态：现在项目状态由项目进度(label)表示 -->
        <Column :label="$t('project.status')" prop="progress" :searchParams="queryParams" :showSearch="true"
                searchType="select" :searchDict="dict.type.project_progress" select-more width="200px"/>
        <!--项目进度：项目进度的 value-->
        <Column :label="$t('project.progress')" prop="progress" width="200px" :searchParams="queryParams"
                :searchDict="getProgressValue(dict.type.project_progress)"
                searchType="select" :showSearch="true" select-more />

        <!--预期安装开始日期-->
        <Column :label="$t('project.expectedInstallStartDate')" prop="expectedInstallStartDate" width="250px"
                :searchParams="queryParams" show-search search-type="dateRange" date-type="daterange"
                prop-start="expectedInstallStartDateStart" prop-end="expectedInstallStartDateEnd"
        />

        <!-- 项目类型 -->
        <Column :label="$t('lead.segment')" prop="type" :searchParams="queryParams" :showSearch="true"
                searchType="select" :searchDict="dict.type.project_type" select-more width="200px"/>
        <!-- 产品系列 -->
        <Column :label="$t('project.projectSegments')" prop="segmentedMarket" :searchParams="queryParams"
                :showSearch="true" searchType="select" :searchDict="dict.type.project_market" select-more
                :selectProp="queryParams.marketParam" width="200px"/>
        <!--项目审批状态:由原来的项目状态表示，只保留了审批通过、不通过、待审批-->
        <Column :label="$t('project.approveStatus')" prop="status" :searchParams="queryParams"
                showSearch searchType="select" :searchDict="dict.type.project_status" select-more
                :selectProp="queryParams.statusParam"
                width="200px">
          <template #default="{ row }">
            <ColorDictTag :bgc="statusColorMap[row.status].bgc"
                          :label="formatDict(row.status, dict.type.project_status)"
                          :label-color="statusColorMap[row.status].color"/>
          </template>
        </Column>
        <!-- 标杆项目 -->
        <Column :label="$t('project.isModel')" prop="modelFlag" :searchParams="queryParams" :showSearch="true"
                searchType="select" :searchDict="dict.type.project_flag" width="200px"/>
        <!-- 最新跟进结果 -->
        <Column :label="$t('account.followDesc')" prop="followDesc" width="250px"/>
        <!-- 负责人 -->
        <Column :label="$t('lead.owner')" prop="ownerName" :searchParams="queryParams" :showSearch="true"
                width="200px"/>
        <!-- 丢单原因 -->
        <Column :label="$t('project.reasonType')" prop="reasonType" :searchParams="queryParams" :showSearch="true"
                searchType="select" :searchDict="dict.type.project_reason_type" width="200px"/>
        <!-- 竞争对手 -->
        <Column :label="$t('project.competitor')" prop="competitor" :searchParams="queryParams" :showSearch="true"
                width="200px"/>
        <!-- 丢单备注 -->
        <Column :label="$t('project.delayLoseRemark')" prop="loseRemark" :searchParams="queryParams" :showSearch="false"
                width="250px">
          <template #default="{ row }">
            <span v-if="row.progress == '0%'">{{ row.delayRemark }}</span>
            <span v-if="row.progress == '0% '">{{ row.loseRemark }}</span>
          </template>
        </Column>
        <!--&lt;!&ndash; 计划成交月份 &ndash;&gt;-->
        <!--<Column :label="$t('account.planDealMonth')" prop="planDealMonth" width="200px" sortable="custom">-->
        <!--  <template #default="{ row }">-->
        <!--    <span>{{ row.planDealMonth ? getLocalTime(row.planDealMonth, 'YYYY-MM') : '-' }}</span>-->
        <!--  </template>-->
        <!--</Column>-->

        <!--&lt;!&ndash; 项目交期 &ndash;&gt;-->
        <!--<Column :label="$t('project.completionYear')" prop="completionYear" width="200px" sortable="custom">-->
        <!--  <template #default="{ row }">-->
        <!--    <span>{{ row.completionYear ? getLocalTime(row.completionYear, 'yyyy-MM-DD') : '-' }}</span>-->
        <!--  </template>-->
        <!--</Column>-->
        <!--&lt;!&ndash; 关联客户 &ndash;&gt;-->
        <!--<Column :label="$t('project.relatedCustomer')" prop="accountName" width="200px" />-->
        <!--&lt;!&ndash; 最新跟进时间 &ndash;&gt;-->
        <!--<Column :label="$t('account.followTime')" prop="followTime" width="250px">-->
        <!--  <template #default="{ row }">-->
        <!--    <span>{{ row.followTime ? getLocalTime(row.followTime, 'YYYY-MM-DD') : '-' }}</span>-->
        <!--  </template>-->
        <!--</Column>-->
        <!--&lt;!&ndash; 跟进人 &ndash;&gt;-->
        <!--<Column :label="$t('account.followPerson')" prop="followPerson" width="200px" />-->
        <!-- 操作 -->
        <Column :label="$t('common.operate')" :min-width="350" fixed="right" :showSearch="true" searchType="operate">
          <template #default="{ row }">
            <!--<el-button size="mini" type="text" icon="el-icon-view" @click="handleView(row)"
              v-hasPermi="['business:project:view']">{{ $t('common.view') }}</el-button>-->

              <!--<el-button size="mini" type="text" icon="el-icon-edit" v-hasPermi="['business:project:edit']"
                         v-if="canEdit(row)" @click="handleCommand('edit', row)">{{ $t('common.edit') }}
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" v-hasPermi="['business:project:remove']"
                         v-if="canDelete(row)" @click="handleCommand('delete', row)">{{ $t('common.delete') }}
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-right" v-if="canFollow(row)"
                         v-hasPermi="['business:project:follow']" @click="handleCommand('follow', row)">{{
                  $t('project.follow')
                }}
              </el-button>
              &lt;!&ndash; 审批 &ndash;&gt;
              <el-button size="mini" type="text" icon="el-icon-edit-outline" v-if="canApprove(row)"
                         @click="handleCommand('approve', row)" v-hasPermi="['business:project:approve']">{{
                  $t('project.approve')
                }}
              </el-button>
              <el-dropdown @command="(command) => handleCommand(command, row)" style="margin-left:5px"
                           v-if="canDelayLost(row) ||  canSetModel(row) || canCancelModel(row) || canChangeOwner(row)"
                           v-hasPermi="[  'business:project:delayLost',  'business:project:setModel', 'business:project:cancelModel', 'business:project:changeOwner']">
                <el-button icon="el-icon-d-arrow-right" size="mini" type="text">
                  {{ $t('common.more') }}
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  &lt;!&ndash; 延期丢单 &ndash;&gt;
                  <el-dropdown-item v-if="canDelayLost(row)" command="delayLost">
                    <el-button size="mini" type="text" icon="el-icon-edit"
                               v-hasPermi="['business:project:delayLost']">{{ $t('project.delayLost') }}
                    </el-button>
                  </el-dropdown-item>
                  &lt;!&ndash; 设为标杆 &ndash;&gt;
                  <el-dropdown-item v-if="canSetModel(row)" command="setModel">
                    <el-button size="mini" type="text" icon="el-icon-s-flag"
                               v-hasPermi="['business:project:setModel']">{{ $t('project.setModel') }}
                    </el-button>
                  </el-dropdown-item>
                  &lt;!&ndash; 设为非标杆 &ndash;&gt;
                  <el-dropdown-item v-if="canCancelModel(row)" command="cancelModel">
                    <el-button size="mini" type="text" icon="el-icon-s-flag"
                               v-hasPermi="['business:project:cancelModel']">{{ $t('project.cancelModel') }}
                    </el-button>
                  </el-dropdown-item>
                  &lt;!&ndash; 更改负责人 &ndash;&gt;
                  <el-dropdown-item v-if="canChangeOwner(row)" command="changeOwner">
                    <el-button size="mini" type="text" icon="el-icon-edit"
                               v-hasPermi="['business:project:changeOwner']">{{ $t('project.changeOwner') }}
                    </el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>-->

            <MoreBtn :handle-command="handleCommand" :row="row" :btns="[
              { label: $t('common.edit'), command: 'edit', icon: 'el-icon-edit', showAble: canEdit(row), permi: 'business:project:edit' },
              { label: $t('common.delete'), command: 'delete', icon: 'el-icon-delete', showAble: canDelete(row), permi: 'business:project:remove' },
              { label: $t('project.follow'), command: 'follow', icon: 'el-icon-right', showAble: canFollow(row), permi: 'business:project:follow' },
              { label: $t('project.approve'), command: 'approve', icon: 'el-icon-edit-outline', showAble: canApprove(row), permi: 'business:project:approve' },
              { label: $t('project.delayLost'), command: 'delayLost', icon: 'el-icon-edit', showAble: canDelayLost(row), permi: 'business:project:delayLost' },
              { label: $t('project.setModel'), command: 'setModel', icon: 'el-icon-s-flag', showAble: canSetModel(row), permi: 'business:project:setModel' },
              { label: $t('project.cancelModel'), command: 'cancelModel', icon: 'el-icon-s-flag', showAble: canCancelModel(row), permi: 'business:project:cancelModel' },
              { label: $t('project.changeOwner'), command: 'changeOwner', icon: 'el-icon-edit', showAble: canChangeOwner(row), permi: 'business:project:changeOwner' },
              { label: $t('account.viewHistory'), command: 'history', icon: 'el-icon-view', permi: 'business:project:view', },
            ]"/>

          </template>
        </Column>
      </template>
    </card-table>

    <ProjectDialog ref="projectForm" :title="title" :visible="open" :type="type" :form="form"
                   @closeDialog="closeDialog">
    </ProjectDialog>

    <el-dialog :title="$t('project.changeOwner')" :visible.sync="changeOwnerOpen" width="500px" append-to-body
               :before-close="cancelChangeOwner" :close-on-click-modal="false">
      <el-form ref="changeOwnerForm" :model="changeOwnerForm" :rules="changeOwnerRules" label-position="top">
        <el-form-item :label="$t('lead.owner')" prop="owner">
          <el-select v-model="changeOwnerForm.owner" clearable filterable
                     :placeholder="$t('common.pleaseSelect') + $t('lead.owner')" style="width: 300px;">
            <el-option v-for="item in ownerList" :key="item.userId" :label="item.nickName" :value="item.userId"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitChangeOwner" icon="el-icon-circle-check" :loading="confirmLoading">
          {{ $t('common.confirm') }}
        </el-button>
        <el-button @click="cancelChangeOwner" icon="el-icon-circle-check">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="$t('project.delayLost')" :visible.sync="delayLostOpen" width="600px" append-to-body
               :before-close="cancelDelayLost" :close-on-click-modal="false">
      <el-form ref="delayLostForm" :model="delayLostForm" :rules="delayLostRules" label-position="top">

        <el-row >
          <el-col :span="12">
            <el-form-item :label="$t('project.delayLost')" prop="status">
              <el-radio-group v-model="delayLostForm.status">
                <el-radio label="09">{{ $t('project.delay') }}</el-radio>
                <el-radio label="10">{{ $t('project.lost') }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <!--原因分类-->
            <Select :label="$t('project.reasonType')" prop="reasonType" required width="100%"
                    :data="dict.type.project_reason_type"/>
          </el-col>
        </el-row>

        <el-row >
          <!-- 竞争对手-->
          <Input :label="$t('project.competitor')" prop="competitor" maxlength="255" required width="100%"/>
        </el-row>


        <!--原因-->
        <el-form-item v-if="delayLostForm.status == '09'" :label="$t('project.reason')" prop="delayRemark">
          <el-input v-model="delayLostForm.delayRemark" type="textarea" maxlength="250" show-word-limit :rows="4"
                    :placeholder="$t('common.pleaseInput') + $t('project.reason')"></el-input>
        </el-form-item>
        <el-form-item v-if="delayLostForm.status == '10'" :label="$t('project.reason')" prop="loseRemark">
          <el-input v-model="delayLostForm.loseRemark" type="textarea" maxlength="250" show-word-limit :rows="4"
                    :placeholder="$t('common.pleaseInput') + $t('project.reason')"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDelayLost" icon="el-icon-circle-check" :loading="confirmLoading">
          {{ $t('common.confirm') }}
        </el-button>
        <el-button @click="cancelDelayLost" icon="el-icon-circle-check">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="$t('project.approve')" :visible.sync="approveOpen" width="600px" append-to-body
               :before-close="cancelApprove" :close-on-click-modal="false">
      <el-form ref="approveForm" :model="approveForm" :rules="approveRules" label-position="top">
        <el-form-item :label="$t('project.approveStatus')" prop="status">
          <el-radio-group v-model="approveForm.status" @change="changeApproveStatus">
            <el-radio label="03">{{ $t('project.pass') }}</el-radio>
            <el-radio label="02">{{ $t('project.notPass') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="approveForm.status === '02'" :label="$t('project.refuseReason')" prop="refuseReason">
          <el-input v-model="approveForm.refuseReason" type="textarea" maxlength="250" show-word-limit :rows="4"
                    :placeholder="$t('common.pleaseInput') + $t('project.refuseReason')"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitApprove" icon="el-icon-circle-check" :loading="confirmLoading">
          {{ $t('common.confirm') }}
        </el-button>
        <el-button @click="cancelApprove" icon="el-icon-circle-check">{{ $t('common.cancel') }}</el-button>
      </div>
    </el-dialog>

    <!-- 更新履历对话框 -->
    <el-dialog :title="$t('account.history')" :visible.sync="historyOpen" width="800px" append-to-body>
      <el-table :data="historyList" max-height="500px" border
                :header-cell-style="{ background: '#F4F6F8', color: '#92A2B5' }">
        <el-table-column type="index" label="No" width="50" align="center"></el-table-column>
        <el-table-column prop="version" :label="$t('common.version')" align="center"
                         width="100"></el-table-column>
        <el-table-column prop="nickName" :label="$t('common.createBy') + '/' + $t('common.updateBy')"
                         align="center" width="200px"></el-table-column>
        <el-table-column prop="modifyRemark" :label="$t('project.modifyRemark')" align="center"
                         width="200px" show-overflow-tooltip ></el-table-column>
        <el-table-column prop="createTime" :label="$t('common.createTime')" align="center"
                         width="200px"></el-table-column>
        <el-table-column :label="$t('common.operate')" width="220px" fixed="right" align="center">
          <template slot-scope="scope">
            <el-button @click="handleViewHistoryInfo(scope.row)" size="mini" type="text"
                       icon="el-icon-view">{{ $t('account.viewHistoryInfo') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination :total="historyTotal" :page.sync="historyQueryParams.pageNum"
                  :limit.sync="historyQueryParams.pageSize" @pagination="getHistoryList"/>
    </el-dialog>

    <FollowDialog ref="followDialog" @returnRow="getList"></FollowDialog>
  </div>
</template>

<script>
import {
  approve,
  changeOwner,
  delayLost,
  delProject,
  getAreaList,
  getCountryList,
  getProject,
  listProject,
  setModel,
  listHistory,
  listProjectNew
} from '@/api/business/crm/project'
import {selectForProject} from "@/api/user/agent";
import {getAllOwnerList, getOwnerList} from '@/api/system/user'
import {getLocalTime} from "@/utils/data/dataUtils"
import ProjectDialog from "../project/dialog";
import FollowDialog from "@/views/crmManagement/follow/FollowDialog";
import ColorDictTag from "@/views/crmManagement/lead/ColorDictTag/index";
import { parseTime } from "@/utils/ruoyi";
import { mapGetters } from 'vuex'
import ImportModal from '@/components/ImportModal/index.vue'
import { comdify, delInput,delcommafy } from "../../../utils/money";
import MoreBtn from '@/components/MoreBtn/index.vue'
const statusColorMap = {
  '01': {
    color: '#FFC500',
    bgc: 'rgba(255,200,12,0.12)'
  },
  '02': {
    color: '#D71943',
    bgc: '#FAEDED'
  },
  '03': {
    color: '#24CA5D',
    bgc: 'rgba(24,199,84,0.12)'
  },
  '09': {
    color: '#FC5821',
    bgc: 'rgba(252,88,33,0.12)'
  },
  '10': {
    color: '#FC5821',
    bgc: 'rgba(252,88,33,0.12)'
  },
  null: {
    color: '#666',
    bgc: 'rgba(0,0,0,0)'
  }
}

export default {
  name: "Project",
  dicts: ['project_flag', 'project_market', 'project_type', 'project_status', 'project_reason_type', 'project_progress',
    'intentional_product', 'currency_type'],
  components: { MoreBtn, ProjectDialog, FollowDialog, ColorDictTag, ImportModal},
  data() {
    return {
      statusColorMap: statusColorMap,
      confirmLoading: false,
      fullLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 项目表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        language: this.$i18n.locale,
        modelFlag: '',
        type: '',
        countryId: '',
        status: '',
        segmentedMarket: '',
        expectedInstallStartDate: '',
      },
      // 表单参数
      form: {},
      areaList: [],
      countryList: [],
      agentList: [],
      type: "",
      language: null,
      ownerList: [],
      changeOwnerOpen: false,
      changeOwnerForm: {},
      changeOwnerRules: {
        owner: [
          {required: true, message: this.$t('common.pleaseSelect') + this.$t('lead.owner'), trigger: "change"},
        ],
      },
      delayLostOpen: false,
      delayLostForm: {},
      delayLostRules: {
        status: [
          {required: true, message: this.$t('common.pleaseSelect') + this.$t('project.delayLost'), trigger: "blur"},
        ],
        reasonType: [
          {required: true, message: this.$t('common.pleaseSelect') + this.$t('project.reasonType'), trigger: "change"},
        ],
        delayRemark:[
          {required: true, message: this.$t('common.pleaseInput') + this.$t('project.reason'), trigger: "blur"},
        ],
        loseRemark:[
          {required: true, message: this.$t('common.pleaseInput') + this.$t('project.reason'), trigger: "blur"},
        ],
      },
      userInfo: {},
      approveOpen: false,
      approveForm: {},
      approveRules: {
        status: [
          {required: true, message: this.$t('common.pleaseSelect') + this.$t('project.approveStatus'), trigger: "blur"},
        ],
        refuseReason: [
          {required: true, message: this.$t('common.pleaseInput') + this.$t('project.refuseReason'), trigger: "blur"},
        ],
      },
      arr:[],
      curProjectId: null,
      historyQueryParams: {
        pageNum: 1,
        pageSize: 10,
        accountId: null,
      },
      historyOpen: false,
      historyList: [],
      historyTotal: 0,
    };
  },
  computed: {
    localLabelSuffix() {
      // return labelSuffix[this.$i18n.locale] || '';
      return localStorage.getItem('labelSuffix') || ''
    },

    showAreaColumn() {
      // VP 、总经理
      // const allowedRoles = ["sales_director", "manager"];
      // return allowedRoles.some(role => this.$store.getters.roles.includes(role));
      // 不可见的角色： 区总、销售经理、代理商经理、代理商销售、销售支持 暂不考虑多角色比如又是销售又是vp角色
      const invisibleRoles = ['area_sales_director', 'sales_manager', 'agent_manager', 'agent_sales', 'sales_support'];
      return !this.$store.getters.roles.some(role => invisibleRoles.includes(role));
    },


    ...mapGetters(['tableMaxHeight']),
    // tableMaxHeight() {
    //   return this.$store.getters.tableMaxHeight
    // },

    pageIndex() {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize
    }
  },
  created() {
    this.language = this.$i18n.locale;
    this.userInfo = this.$store.state.user.userInfo;
    this.getList();
    // this.getAreaList();
    // this.getNationList();
    this.getAgentList();
    this.getOwnerList();

    this.listenRefreshListVuex();
  },
  methods: {
    getProgressValue(x){
      let arr = []
      for (let i = 0; i < x.length; i++) {
        arr.push({
          label:x[i].value,
          value:x[i].value
        })
      }
      return arr;
    },
    parseTime,
    getLocalTime,
    handleCommand(command, row) {
      switch (command) {
        case "edit":
          this.handleUpdate(row)
          break;
        case "delete":
          this.handleDelete(row)
          break;
        case "approve":
          this.handleApprove(row)
          break;
        case "delayLost":
          this.handleDelayLost(row)
          break;
        case "follow":
          this.handleFollow(row)
          break;
        case "setModel":
          this.handleSetModel(row)
          break;
        case "cancelModel":
          this.handleCancelModel(row)
          break;
        case "changeOwner":
          this.handleChangeOwner(row)
          break;
        case "history":
          this.handleViewHistory(row)
          break;
      }
    },
    handleViewHistory(row) {
      this.historyQueryParams.pageNum = 1;
      this.curProjectId = row.projectId;
      this.getHistoryList();
      this.historyOpen = true;
    },
    handleViewHistoryInfo(row) {
      this.historyOpen = false;
      this.$tab.openPage(this.$t('project.view'), '/project-view/' + row.projectId,
        {type: 'view', projectId: row.projectId, version: row.version});
    },
    getHistoryList() {
      this.historyQueryParams.projectId = this.curProjectId;
      listHistory(this.historyQueryParams).then(response => {
        this.historyList = response.rows;
        this.historyTotal = response.total;
      })
    },
    getAreaList() {
      getAreaList().then(res => {
        this.areaList = res.data;
      })
    },
    getOwnerList() {

      if (this.$store.getters.roles.includes('sales_director')) {
        getAllOwnerList({onlySalesRole: true}).then(res => {
          this.ownerList = res.data;
        })
      } else {
        getOwnerList({onlySalesRole: true}).then(res => {
          this.ownerList = res.data;
        })
      }

    },
    getAgentList() {
      selectForProject().then(res => {
        this.agentList = res.data;
        if (this.userInfo.deptId == 0) {
          this.agentList.unshift({agentId: 0, agentName: this.$t('common.head')});
        }
      })
    },
    canApprove(row) {
      return row.status == '01' && this.userInfo.deptId === 0 && row.parentSaleId === this.$store.getters.userId
    },
    /** 当前项目是否可以编辑 */
    canEdit(row) {
      return this.$store.getters.roles.includes('sales_director')
        || row.owner === this.$store.getters.userId
        || this.$store.getters.roles.includes('admin')
        || this.$store.getters.roles.includes('area_sales_director');
      // return checkRole(['sales_director']) || row.owner === this.$store.getters.userId;

      // let flag = true;
      //  //销售VP角色，可以任意操作
      //  if(this.$store.state.user.roles.includes('sales_director')){
      //           return true
      //       }
      // let permissionArray = this.userInfo.permissionChar.split(',');
      // let rowPermissionArray = row.permissionChar.split(',');
      // for (let i = 0; i < rowPermissionArray.length; i++) {
      //   if (!permissionArray.includes(rowPermissionArray[i])) {
      //     flag = false;
      //     break;
      //   }
      // }
      // return flag;
    },
    specialPer() {
      return this.$store.getters.roles.includes('sales_director') || this.$store.getters.roles.includes('admin');
    },
    canDelete(row) {
      // return (row.status == '01' || row.status == '02') && this.canEdit(row)
      return ((row.status == '01' || row.status == '02') && this.canEdit(row)) || this.specialPer()
    },
    canDelayLost(row) {
      return row.status != '01' && row.status != '02' && row.progress != '0%' && row.progress != '0% ' && this.canEdit(row)
    },
    canFollow(row) {
      return row.status != '01' && row.status != '02' && this.canEdit(row)
    },
    canSetModel(row) {
      return row.modelFlag != '1' && row.status != '02'
    },
    canCancelModel(row) {
      return row.modelFlag != '0' && row.status != '02'
    },
    canChangeOwner(row) {
      return row.status != '02' && row.status != '10' && (row.deptId === this.$store.state.user.userInfo.deptId || this.$store.getters.roles.includes('sales_director'))
    },
    /** 获取所有国家列表 */
    getNationList() {
      getCountryList().then(response => {
        this.countryList = response.data
      })
    },
    /** 获取字典数据匹配的值 */
    formatDict(value, dictData) {
      return dictData.find(dict => dict.value == value)?.label;
    },
    /** 查询项目列表 */
    async getList() {
      this.loading = true;
      try {
        //const response = await listProject(this.queryParams);
        const response = await listProjectNew(this.queryParams);
        this.projectList = response.rows;
        this.queryParams.total = response.total;
        if (response.rows && response.rows.length > 0) this.setTableIndex(this.projectList);
      } finally {
        this.loading = false;
      }

      // listProject(this.queryParams).then(response => {
      //   this.projectList = response.rows;
      //   this.queryParams.total = response.total;
      //   this.loading = false;
      // });

      this.getAreaList();
      this.getNationList();
    },

    // 树形列表index层级，实现方法（可复制直接调用）
    setTableIndex(arr, index) {
      arr.forEach((item, ind) => {
        item.index = this.pageIndex + ind + 1;
        if (index) {
          item.index = index + "-" + (ind + 2);
        }
        if (item.children) {
          this.setTableIndex(item.children, item.index);
        }
      });
    },

    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        language: this.$i18n.locale,
        modelFlag: '',
        type: '',
        countryId: '',
        status: '',
        progress: '',
        segmentedMarket: ''
      }
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId)
      // this.single = selection.length !== 1
      // this.multiple = !selection.length
    },

    sortChange({column, prop, order}) {
      if (order === 'ascending') {
        this.queryParams.orderByColumn = prop;
        this.queryParams.isAsc = 'asc';
      } else if (order === 'descending') {
        this.queryParams.orderByColumn = prop;
        this.queryParams.isAsc = 'desc';
      } else {
        this.queryParams.orderByColumn = null;
        this.queryParams.isAsc = null;
      }
      this.getList();
    },

    async setFormData(row) {
      this.fullLoading = true;
      await getProject(row.projectId).then(response => {
        this.form = response.data;
        this.form.accountId = this.form.accountId + "";
        this.$refs.projectForm.defaultData = [{
          accountId: response.data.accountId,
          accountNo: response.data.accountNo,
          accountName: response.data.accountName,
          areaId: response.data.areaId,
          countryId: response.data.countryId
        }]
        if (!this.form.machineList) {
          this.form.machineList = []
        }else {
          this.form.machineList.some(item=>{
            item.amount = comdify(delcommafy(item.amount), 2);

          })
        }
        this.$refs.projectForm.myLeadList = this.form.leadList
        this.fullLoading = false;
        this.open = true;
        this.$refs.projectForm.getRelatedContact(this.form.accountId);
      }).catch(() => {
        this.fullLoading = false;
      });
    },
    /** 更改负责人 */
    handleChangeOwner(row) {
      this.changeOwnerForm = {
        projectId: row.projectId,
        owner: row.owner,
        updateTime: row.updateTime,
        modifyRemark: this.$t('project.changeOwner')
      }
      this.changeOwnerOpen = true;
    },
    cancelChangeOwner() {
      // this.resetForm("changeOwnerForm");
      this.changeOwnerOpen = false;
    },
    submitChangeOwner() {
      this.$refs["changeOwnerForm"].validate(valid => {
        if (valid) {
          this.confirmLoading = true;
          changeOwner(this.changeOwnerForm).then(response => {
            if (response.code == 200) {
              this.$modal.msgSuccess(this.$t('common.editSuccess'));
              this.cancelChangeOwner();
              this.getList();
            } else {
              this.$modal.msgError(response.msg);
            }
          }).catch(() => {
          });
          this.confirmLoading = false;
        }
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.$tab.openPage(this.$t('project.view'), '/project-view/' + row.projectId);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      if (this.$store.getters.userId != 1) {
        this.$set(this.form, 'owner', this.$store.getters.userId);
      }
      this.$set(this.form, 'machineList', []);
      this.title = this.$t('project.addProject');
      this.type = 'add';
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title = this.$t('project.editProject');
      this.type = 'edit';
      this.setFormData(row);
    },
    closeDialog(e) {
      this.open = false;
      if (e) {
        this.getList();
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm(this.$t('common.isDelete')).then(() => {
        this.fullLoading = true;
        delProject(row.projectId).then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t('common.deleteSuccess'));
          this.fullLoading = false;
        })
      }).catch(() => {
        this.fullLoading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      // this.queryParams.ids = this.ids;
      this.queryParams.language = this.$i18n.locale;
      let fileName = this.$t('index.guideFour') + parseTime(new Date(), '{y}{m}{d}') + '.xlsx'
      this.download('business/project/export', {
        ...this.queryParams,
        ids: this.ids || null
      }, fileName)
    },
    changeApproveStatus() {
      this.$set(this.approveForm, 'refuseReason', null);
    },
    /** 延期/丢单 */
    handleDelayLost(row) {
      this.delayLostForm = {
        projectId: row.projectId,
        updateTime: row.updateTime
      }
      this.delayLostOpen = true;
    },
    /** 设为标杆 */
    handleSetModel(row) {
      const that = this
      this.$modal.confirm(this.$t('project.confirmSetModel')).then(function () {
        return setModel({projectId: row.projectId, modelFlag: '1', updateTime: row.updateTime, modifyRemark: that.$t('project.setModel')});
      }).then((response) => {
        if (response.code == 200) {
          this.$modal.msgSuccess(this.$t('common.editSuccess'));
          this.getList();
        } else {
          this.$modal.msgError(response.msg);
        }
      })
    },
    /** 设为非标杆 */
    handleCancelModel(row) {
      const that = this
      this.$modal.confirm(this.$t('project.confirmCancelModel')).then(function () {
        return setModel({projectId: row.projectId, modelFlag: '0', updateTime: row.updateTime, modifyRemark: that.$t('project.cancelModel')});
      }).then((response) => {
        if (response.code == 200) {
          this.$modal.msgSuccess(this.$t('common.editSuccess'));
          this.getList();
        } else {
          this.$modal.msgError(response.msg);
        }
      })
    },
    cancelDelayLost() {
      this.$refs["delayLostForm"].resetFields();
      this.delayLostOpen = false;
    },
    /** 提交延期/丢单 */
    submitDelayLost() {
      this.$refs["delayLostForm"].validate(valid => {
        if (valid) {
          this.confirmLoading = true;
          if (this.delayLostForm.status == '09') {
            delete this.delayLostForm.loseRemark
          } else if (this.delayLostForm.status == '10') {
            delete this.delayLostForm.delayRemark
          }
          delayLost(this.delayLostForm).then(response => {
            if (response.code == 200) {
              this.$modal.msgSuccess(this.$t('common.editSuccess'));
              this.cancelDelayLost();
              this.getList();
            } else {
              this.$modal.msgError(response.msg);
            }
          }).catch(() => {
          });
          this.confirmLoading = false;
        }
      });
    },
    /** 跟进 */
    handleFollow(row) {
      this.$refs.followDialog.dialogItemInit({flag: '1', projectId: row.projectId})
    },
    /** 审批 */
    handleApprove(row) {
      this.approveForm = {
        projectId: row.projectId,
        updateTime: row.updateTime
      }
      this.approveOpen = true;
    },
    cancelApprove() {
      this.$refs["approveForm"].resetFields();
      this.approveOpen = false;
    },
    /** 提交审批 */
    submitApprove() {
      this.$refs["approveForm"].validate(valid => {
        if (valid) {
          this.confirmLoading = true;
          approve(this.approveForm).then(response => {
            if (response.code == 200) {
              this.$modal.msgSuccess(this.$t('common.editSuccess'));
              this.cancelApprove();
              this.getList();
            } else {
              this.$modal.msgError(response.msg);
            }
          }).catch(() => {
          });
          this.confirmLoading = false;
        }
      });
    },

    /*  */
    listenRefreshListVuex() {
      this.$store.subscribe((mutation) => {
        if (mutation.type === 'refreshProject') {
          this.getList()
        }
      })
    },

    isChildRow({row, rowIndex}) {

      if (row.rowKey != row.projectId) {
        return 'is-child-row'
      }
    }
  }
};
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
::v-deep .el-form-item--medium .el-form-item__label {
  line-height: 12px;
}
</style>
