<template>

  <div class="unfollowed-container">

    <!-- 未跟进项目列表 -->
    <div class="unfollowed-list">
      <div class="chart-box-title">
      <span>{{ $t('board.leadCountStat') }}</span>

      <el-select v-model="statMode" :placeholder="$t('common.pleaseSelect')" style="width: 100px;"
                 @change="leadStatModeChange">
        <el-option :label="$t('board.year')" value="year"></el-option>
        <el-option :label="$t('board.month')" value="month"></el-option>
        <el-option :label="$t('board.day')" value="day"></el-option>
      </el-select>

      <date-picker v-if="statMode === 'year'" v-model="query.leadDateRange" :end-placeholder="$t('common.endYear')"
                   :start-placeholder="$t('common.startYear')" range-separator="~"
                   type="yearrange"
                   value-format="yyyy-MM-dd"/>
      <el-date-picker v-if="statMode === 'month'" v-model="query.leadDateRange"
                      :end-placeholder="$t('common.endMonth')" :start-placeholder="$t('common.startMonth')"
                      range-separator="~"
                      type="monthrange" value-format="yyyy-MM-dd"/>
      <el-date-picker v-if="statMode === 'day'" v-model="query.leadDateRange" :end-placeholder="$t('common.endDay')"
                      :start-placeholder="$t('common.startDay')" range-separator="~"
                      type="daterange" value-format="yyyy-MM-dd"/>

      <div class="buttons">
        <el-button size="mini" type="primary" @click="getList">{{ $t('common.search') }}</el-button>
        <el-button size="mini" @click="reset">{{ $t('common.reset') }}</el-button>
      </div>
    </div>
      <div class="table-wrapper">
      <el-table v-loading="loading" :data="projectList" :height="height"
                :header-cell-style="{'text-align':'center','background-color':'#F4F3F2','border-right':'1px solid #dfdcdc'}"
                border stripe
      >
        <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="false" fixed 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="false" fixed
                width="250px"/>
        <!-- 区域 -->
        <Column v-if="showAreaColumn" :label="$t('user.area')" prop="areaId" :searchParams="queryParams"
                :searchDict="areaList" :showSearch="false" valueProp="first" labelProp="second"
                searchType="select" selectMore width="200px"/>
        <!-- 国家 -->
        <Column :label="$t('account.country')" prop="countryId" :searchParams="queryParams" :showSearch="false"
                valueProp="first" labelProp="second" searchType="select"
                :searchDict="countryList" select-more width="200px"/>
        <!-- 城市 -->
        <Column :label="$t('project.city')" prop="city" :searchParams="queryParams" :showSearch="false" width="200px"/>

        <!--所属代理商-->
        <Column :label="$t('lead.agent')" prop="ownerAgent" :showSearch="false" 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>

        <!--设备总数-->
        <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>

        <!-- 项目类型 -->
        <Column :label="$t('lead.segment')" prop="type" :searchParams="queryParams" :showSearch="false"
                searchType="select" :searchDict="dict.type.project_type" select-more width="200px"/>
        <!-- 产品系列 -->
        <Column :label="$t('project.projectSegments')" prop="segmentedMarket" :searchParams="queryParams"
                :showSearch="false" searchType="select" :searchDict="dict.type.project_market" select-more
                :selectProp="queryParams.marketParam" width="200px"/>

        <!-- 标杆项目 -->
        <Column :label="$t('project.isModel')" prop="modelFlag" :searchParams="queryParams" :showSearch="false"
                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="false"
                width="200px"/>
        <!-- 丢单原因 -->
        <Column :label="$t('project.reasonType')" prop="reasonType" :searchParams="queryParams" :showSearch="false"
                searchType="select" :searchDict="dict.type.project_reason_type" width="200px"/>
        <!-- 竞争对手 -->
        <Column :label="$t('project.competitor')" prop="competitor" :searchParams="queryParams" :showSearch="false"
                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>
      </el-table>
      <pagination :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum"
                  :total="queryParams.total"
                  @pagination="getList"/>
      </div>
    </div>

  </div>

</template>

<script>
import {
  approve,
  changeOwner,
  delayLost,
  delProject,
  getAreaList,
  getCountryList,
  getProject,
  listProjectBoard,
  listProject,
  setModel,
  listHistory
} 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 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'
import moment from "moment-timezone";
import DatePicker from '@/components/YearDatePicker/date-picker'
export default {
  name: "LossProject",
  dicts: ['project_flag', 'project_market', 'project_type', 'project_status', 'project_reason_type', 'project_progress',
    'intentional_product', 'currency_type'],
  components: { MoreBtn, FollowDialog, ColorDictTag, ImportModal,DatePicker},
  props: {
    height: {
      type: String,
      default: '30vh'
    }
  },
  data() {
    return {
      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: '',
        searchType:"1",
        total: 0,
      },
      // 表单参数
      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,
      statMode: 'month',
      query: {
        leadDateRange:  []
      },
      rules: {
        statMode: [
        ],
        leadDateRange: [
          {required: true, message: '请选择统计时间范围', trigger: 'change'}
        ]
      }
    };
  },
  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
    },
    compDateRangeLabel() {
      return {
        year: this.$t('board.queryY'),
        month: this.$t('board.queryM'),
        day: this.$t('board.queryD'),
      }[this.statMode]
    }
  },
  created() {

    // 默认最近半年
    this.resetDate()
    this.$nextTick(async () => {

      await this.getList();

      this.getAgentList();
      this.getOwnerList();
    })


    this.listenRefreshListVuex();
  },
  methods: {
    leadStatModeChange(val) {
      // console.log(val)
      // console.log(this.statMode)
      if (!val) {
        return
      }
      switch (val) {
        case 'year':
          // 当年第一天到今天
          this.query.leadDateRange = [moment().startOf('year').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
          break
        case 'month':
          // 当月第一天到今天
          this.query.leadDateRange = [moment().startOf('month').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
          break
        case 'day':
          // 当天
          this.query.leadDateRange = [moment().format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
          break
      }
    },

    resetDate() {
      // this.$refs.ruleForm.resetFields()
      this.statMode = 'month'
      // 获取六个月前的日期
      const sixMonthsAgo = moment().subtract(6, 'months')
      // 获取六个月前所在月的第一天
      const startDate = sixMonthsAgo.startOf('month').format('YYYY-MM-DD')
      // 获取今天的日期
      const endDate = moment().format('YYYY-MM-DD')
      // 设置日期范围
      this.query.leadDateRange = [startDate, endDate]
    },

    reset() {
      this.resetDate()
      // 获取列表
      this.getList()
    },
    modeChange(e) {
      this.getList();
    },
    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,

    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')});
        }
      })
    },

    /** 获取所有国家列表 */
    getNationList() {
      getCountryList().then(response => {
        this.countryList = response.data
      })
    },
    /** 获取字典数据匹配的值 */
    formatDict(value, dictData) {
      return dictData.find(dict => dict.value == value)?.label;
    },
    /** 查询项目列表 */
    async getList() {
      this.loading = true;
      this.$set(this.queryParams,"progress",['0%','0% '])
      this.$set(this.queryParams,"startDate",this.query.leadDateRange[0])
      this.$set(this.queryParams,"endDate",this.query.leadDateRange[1])
      // this.queryParams.progress = ['0%','0% ']
      try {
        const response = await listProjectBoard(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);
        }
      });
    },

    /** 搜索按钮操作 */
    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" scoped>
  //.app-container {
  .unfollowed-container {
    //padding: 1.5vw;
    //background-color: #fff;

    .title {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 20px;
    }

    .search-row {
      margin-bottom: 1.5vw;
    }

    .count-wrapper {
      .count-box {
        height: 10vw;
        width: 15vw;
        border: 1px solid #BBBBBB;
        border-radius: 4px;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 1.5vw;

        .count-content {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          gap: 1vw;

          span {
            font-size: 16px;
            font-weight: bold;
          }
        }
      }
    }

    .pie-chart-wrapper {
      .pie-chart {
        height: 20vw;
        width: 20vw;
      }
    }

    .unfollowed-list {
      .unfollowed-list-title {
        padding: .5rem;
        font-size: 16px;
        font-weight: bold;

        margin-bottom: 24px;
        white-space: nowrap;
        display: flex;
        align-items: center;
        gap: 1vw;
        background-color: #f5f5f5;
      }
      .chart-box-title {
        padding: .5rem;
        font-size: 16px;
        font-weight: bold;
        background-color: #f5f5f5;
        display: flex;
        align-items: center;
        gap: 1rem;
        margin-bottom: 24px;
        .buttons {
          margin-left: auto;
        }
      }
    }

    .table-wrapper {
      //width: 80%;
      //padding: 24px;
      padding-bottom: 24px;
      //margin-top: 16px;
      background: #FFFFFF;
      //box-shadow: 0px 2px 10px 0px #CED6DD;
      border-radius: 6px;
    }
  }

</style>
