<template>
  <div class="bargainList pagePadding">
    <div
      v-if=" powers.some((i) => i == '001')"
    >
      <ex-table
        v-loading="loading"
        :table="table"
        :data="tableData"
        :columns="columns"
        :page="pageInfo"
        :size="size"
        @page-curr-change="handlePageChange"
        @page-size-change="handleSizeChange"
        @screen-reset="
          pageInfo.curr = 1;
          parmValue.page = 1;
          searchList();
        "
        @screen-submit="
          pageInfo.curr = 1;
          parmValue.page = 1;
          searchList();
        "
      >
        <template #table-header="{}">
          <div style="width: 100%">
            <el-row style="padding: 0 0 0 80px">
              <el-col :span="4" style="width: 351px;">
                <period-date-picker
                  :start="parmValue.addtime_start"
                  :end="parmValue.addtime_end"
                  :width="'160px'"
                  :size="searchSize"
                  placeholder="创建"
                  @timeReturned="(evt) => handleTime(evt,'create')"
                />
              </el-col>

              <el-col :span="6" style="padding-left:10px">
                <search-customer style="width:100%" size="mini" placeholder="客户公司" :value.sync="parmValue.req_corp" @change="
                  pageInfo.curr = 1;
                  parmValue.page = 1;
                  searchList();
                  " 
                />
              </el-col>
                            
              <el-col :span="3" style="width: 66px; float: right">
                <el-button
                  :size="searchSize"
                  type="primary"
                  style="float: right; margin-left: 5px"
                  @click="searchList"
                >
                  刷新
                </el-button>
              </el-col>
              <el-col :span="4" class="fr" style="width: 66px">
                <el-button
                  type="warning"
                  class="fr"
                  :size="searchSize"
                  @click="restSearch"
                >
                  重置
                </el-button>
              </el-col>
            </el-row>

            <el-row style="margin-top:10px">
              <!-- <el-col :span="4" style="width: 341px;">
                <period-date-picker
                  :start="parmValue[act_start]"
                  :end="parmValue[act_end]"
                  :width="'154px'"
                  :size="searchSize"
                  @timeReturned="evt => handleTime(evt,'activity')"
                  placeholder="活动"
                />
              </el-col> -->

              <el-col :span="4" style="padding-right:10px">
                <el-select v-model="parmValue.status" style="width:100%" size="mini" placeholder="订单状态" @change="
                pageInfo.curr = 1;
                parmValue.page = 1;
                searchList();
               ">
                  <el-option 
                    v-for="status in demandStatusOptions" 
                    :key="status.value" 
                    :value="status.value" 
                    :label="status.label"
                   />
                </el-select>
              </el-col>

              <el-col :span="4" style="padding-right:10px">
                <search-people-number style="width:100%" size="mini" 
                  :value.sync="parmValue.participant"
                  placeholder="活动人数"  
                  @change="
                  pageInfo.curr = 1;
                  parmValue.page = 1;
                  searchList();
                " />
              </el-col>

               <el-col :span="4" style="padding-right:10px">
                <el-input size="mini" placeholder="需求编号" v-model="parmValue.reqCode" @change="
                  pageInfo.curr = 1;
                  parmValue.page = 1;
                  searchList();
               "/>
              </el-col>

              <el-col :span="4" style="padding-right:10px">
                <el-input v-model="parmValue.req_tel" size="mini" placeholder="联系电话" @change="
                  pageInfo.curr = 1;
                  parmValue.page = 1;
                  searchList();
               "/>
              </el-col>

              <!-- <el-col :span="4">
                <search-demand style="width:100%" size="mini" :value.sync="parmValue.participant"  @change="
                  pageInfo.curr = 1;
                  parmValue.page = 1;
                  searchList();
                " />
              </el-col> -->
            </el-row>

            <!-- <el-row style="margin-top:10px"> -->
  

              <!-- <el-col :span="4">
                <search-activity-type style="width:100%" size="mini" :value.sync="parmValue.req_demand" placeholder="需求项目" @change="
                   pageInfo.curr = 1;
                   parmValue.page = 1;
                   searchList();
                  " 
                />
              </el-col> -->
            <!-- </el-row> -->

            <!-- <el-row style="margin-top:10px"> -->

              <!-- <el-col :span="4">
                <el-input size="mini" placeholder="需求创建人" v-model="parmValue.req_user_id" @change="
                pageInfo.curr = 1;
                parmValue.page = 1;
                searchList();
               "/>
              </el-col> -->
            <!-- </el-row> -->

          </div>
        </template>
        <template #req_demand="{scope}">{{
          scope.row.req_demand_name.map(({name}) => name).join("+") || '--'
          }}</template>

          <template #actTime="{ scope }">
            {{getActTime(scope.row)}} , 共{{scope.row.act_day_count}}天
          </template>

          <template #participant="{ scope }">
            <span v-if="Number(scope.row.participant_max) === 0">{{
              scope.row.participant_min
            }}+</span>

            <span v-else>
              {{scope.row.participant_min}} ~ {{scope.row.participant_max}}
            </span> 人
          </template>
        <template #status="{ scope }">
          <el-tag
            size="mini"
            v-text="
              (demandStatusOptions.find((item) => item.value == String(scope.row.status)) || {})
                .label || '--'
            "
          ></el-tag>
        </template>
        <template #operation="{ scope }">
          <el-tooltip
            effect="dark"
            content="详情"
            placement="top"
          >
            <i
              class="el-icon-view tb-icon"
               @click="getRouter('demandOrderDetail', scope.row.id)"
            ></i>
          </el-tooltip>

          <el-tooltip :content="'联系电话 : ' + scope.row.req_tel" placement="top">
            <i class="el-icon-phone-outline tb-icon" />
          </el-tooltip>
        </template>
      </ex-table>
    </div>
    <div v-else>
      <no-auth></no-auth>
    </div>
  </div>
</template>
<script>
import mixinPage from "@/mixins/elPaginationHandle";
import resToken from "@/mixins/resToken";
import asyncRequest from "@/apis/service/customerService/demandOrder";
import companyHelper from "@/mixins/companyHelper"
import { listCol, statusList } from "./columns";
import { mapGetters } from "vuex";
import { demandStatusOptions } from '@/assets/js/statusList';
import dayjs from "dayjs"

/**
* @props
 创建时间开始&结束
  addtime_start //创建开始时间
  addtime_end //创建结束时间
  act_start //活动开始时间
  act_end //活动结束时间
  req_start //咨询开始时间
  req_end //咨询结束时间
  participant'//活动人数,
  city //活动城市,
  status //订单状态,
  req_tel //联系电话
  participant //活动需求
  reqCode //需求编号
  req_demand //需求项目
  req_user_id //需求创建人
  demandEnterprise //需求企业
**/

const mapDateFields = {
  create: {
    start:'addtime_start',
    end:"addtime_end",
    label:'创建'
  },
  activity:{
    start:'act_start',
    end:"act_end",
    label:'活动'
  },
  consultation:{
    start:"req_start",
    end:"req_end",
    label:'咨询'
  }
}

export default {
  name: "bargainList",
  mixins: [mixinPage, resToken, companyHelper],
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),
    powers() {
      const tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "demandOrder"
        ) || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    return {
      select: "1",
      s_input: "",
      demandStatusOptions,
      customerCode: [], //客户公司code
      statusList,
      sitem: null,
      loading: true,
      showModel: false,
      isDetail: false,
      modelId: 0,
      parmValue: {
        addtime_start:"", //创建开始时间
        addtime_end:"", //创建结束时间
        act_start:"", //活动开始时间
        act_end:"", //活动结束时间
        req_start:"", //咨询开始时间
        req_end:"", //咨询结束时间
        participant:"",//活动人数
        city:"", //活动城市,
        status:"", //订单状态,
        req_tel:"", //联系电话
        reqCode:"", //需求编号
        req_demand:"", //需求项目
        req_user_id:"", //需求创建人
        demandEnterprise:"", //需求企业
        page: 1, // 页码
        size: 15, // 每页显示条数
      },
      // 表格 - 数据
      tableData: [],
      // 表格 - 参数
      table: {
        stripe: true,
        border: true,
        _defaultHeader_: ["setcol"],
      },
      // 表格 - 分页
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0,
      },
      // 表格 - 列参数
      columns: listCol,

      resultValue: "", //处理结果
    };
  },
  mounted() {
    const { back } = this.$route.query;
    if (back) {
      this.parmValue = JSON.parse(back);
      const {page,size}=this.parmValue;
       this.pageInfo= {
        size: size,
        curr: page,
        total: 0,
      }
    }else{
       this.select = "1";
    }
    this.searchList();
  },

  methods: {
    getRouter(toRouter, queryId){
      if (toRouter && queryId) {
        let model = {
          id: queryId,
          type: 'view',
        };

        //有多选框的条件
        this.parmValue.select = this.select ;
        this.parmValue.s_input= this.s_input;
        //
         let routerModel = {
          options: JSON.parse(JSON.stringify(this.parmValue)),
          router: this.$route.path,
        };
        model.preModel = JSON.stringify(routerModel);
        
        this.routeGoto(toRouter, model);
      } else {
        this.$message.warning("暂未找到相关流程！");
      }
    },
    restSearch() {
      this.customerCode = [];
      this.select = "1";
      this.s_input = "";
      this.parmValue = {
        addtime_start:"", //创建开始时间
        addtime_end:"", //创建结束时间
        act_start:"", //活动开始时间
        act_end:"", //活动结束时间
        req_start:"", //咨询开始时间
        req_end:"", //咨询结束时间
        participant:"",//活动人数 TODO...
        city:"", //活动城市,
        status:"", //订单状态,
        req_tel:"", //联系电话
        participant:"", //活动需求 TODO...
        reqCode:"", //需求编号
        req_rorp:"", //需求项目 TODO...
        req_user_id:"", //需求创建人 TODO...
        demandEnterprise:"", //需求企业 TODO...
        page: 1, // 页码
        size: 15, // 每页显示条数
      };
      // 表格 - 分页
      this.pageInfo = {
        size: 15,
        curr: 1,
        total: 0,
      };
      this.searchList();
    },

    openModal(id, isDetail, sitem) {
      this.showModel = true;
      this.modelId = id;
      this.isDetail = isDetail;
      this.sitem = sitem;
    },
    async deleteById(id, status) {
      await this.$confirm("确定要删除？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
          const model = {
            id: id,
            status: status + '' === "1" ? "0" : "1",
          };
          const res = await asyncRequest.status(model);
          if (res && res.code === 0) {
            this.$notify.success({
              title: "删除成功",
              message: "",
            });
            this.searchList();
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },
    getActTime(item){
      const { act_time, act_day_count } = item;
      const end_time = dayjs(act_time).subtract(Number(act_day_count) - Number(act_day_count) * 2,'day').format('MM.DD')
      return `${dayjs(act_time).format('MM.DD')} ~ ${end_time}`
    },
    // 列表搜索
    async searchList() {
      for(const field of Object.keys(mapDateFields)){
        const { start:startProp, end:endProp, label } = mapDateFields[field]

        if (
          (this.parmValue[startProp] !== "" && this.parmValue[endProp] === "") ||
          (this.parmValue[startProp] === "" && this.parmValue[endProp] !== "")
          ) {
            this.$message.warning(`${label}时间区间不完整！`);
            return;
          }
      }

      this.loading = true;
      
      const res = await asyncRequest.list({
        ...this.parmValue,
      });

      if (res && res.code === 1 && res.data) {
        this.tableData = res.data.list;
        this.pageInfo.total = Number(res.data.count);
      } else {
        this.tableData = [];
        this.pageInfo.total = 0;
      }
      this.loading = false;
    },

    async statusConfirm(id, status) {
      let str = status + '' === "1" ? "禁用" : "启用";
      await this.$confirm("确定要改为" + str + "?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          this.loading = true;
          const model = {
            id: id,
            status: status + '' === "1" ? "0" : "1",
          };
          const res = await asyncRequest.status(model);
          if (res && res.code === 0) {
            this.loading = false;
            this.$notify.success({
              title: "状态修改成功！",
              message: "",
            });
            await this.searchList();
          } else if (res && res.code >= 100 && res.code <= 104) {
            await this.logout();
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },
    // 时间选择事件
    async handleTime(e,field) {
      const {start:startProp,end:endProp } = mapDateFields[field]
      if (e.startTime !== "") {
        this.parmValue[startProp] = e.startTime;
      } else {
        this.parmValue[startProp] = "";
      }
      if (e.endTime !== "") {
        this.parmValue[endProp] = e.endTime;
      } else {
        this.parmValue[endProp] = "";
      }
      if (this.parmValue[startProp] !== "" && this.parmValue[endProp] !== "") {
        this.pageInfo.curr = 1;
        this.parmValue.page = 1;
        await this.searchList();
      }
    },
    async customerChange(e) {
      const { code } = e;
      this.parmValue.customer_code = code ? [code] : [];
      this.parmValue.supplierName = e.label;
      this.pageInfo.curr = 1;
      this.parmValue.page = 1;
      await this.searchList();
    },
  },
};
</script>
   <style lang="scss" scoped>
.bargainList {
}
</style>
   