<template>
  <base-list>
    <template slot="n_header">
      <el-form v-model="pagerDto" inline>
        <el-form-item label="客户">
          <el-select
            v-model="pagerDto._Co_CustomerIds"
            placeholder="客户名称"
            clearable
            filterable
            class="item-form"
          >
            <el-option
              v-for="item in customers"
              :key="item.Id"
              :label="item.CompanyName"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="主渠道">
          <el-select
            v-model="pagerDto._Eq_ExpressId"
            placeholder="主渠道"
            clearable
            filterable
            class="item-form"
          >
            <el-option
              v-for="(item,index) in publicChannels"
              :key="`${item.Id}_${index}`"
              :label="item.Name"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建用户">
          <el-select
            v-model="pagerDto._Eq_CreateUserName"
            placeholder="创建用户"
            clearable
            filterable
            class="item-form"
          >
            <el-option
              v-for="item in users"
              :key="item.Id"
              :label="item.Name"
              :value="item.Name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间大于">
          <el-date-picker v-model="pagerDto._GrE_CreateTime" value-format="yyyy-MM-dd" class="item-form" />
        </el-form-item>

        <el-form-item label="创建时间小于">
          <el-date-picker v-model="pagerDto._LeE_CreateTime" value-format="yyyy-MM-dd" class="item-form" />
        </el-form-item>
        <el-form-item label="生效时间">
          <el-date-picker v-model="pagerDto._Eq_EnableTime" value-format="yyyy-MM-dd" class="item-form" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="pagerDto._Eq_Status"
            placeholder="状态"
            clearable
            filterable
            class="item-form"
          >
            <el-option
              v-for="item in Statuses"
              :key="item.Id"
              :label="item.Name"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="pagerSerach(1)" :loading="dataLoading">搜索</el-button>
          <el-button type="success" @click="exportRecord" :loading="exportLoading">导出</el-button>
          <el-button v-if="getAdminRoles" type="info" @click="batchApproval" :loading="batchLoading">批量审批</el-button>
        </el-form-item>
      </el-form>
    </template>
    <template slot="n_option" />
    <template>
      <el-table
        v-loading="dataLoading"
        :data="data"
        :highlight-current-row="true"
        :select-on-indeterminate="true"
        width="100%"
        @expand-change="expandChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="46">
        </el-table-column>
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-table v-loading="props.row.LoadingDetails" :data="props.row.Details">
              <el-table-column prop="StartWeight" label="开始重量/KG" />
              <el-table-column prop="EndWeight" label="结束重量/KG" />
              <el-table-column prop="Freight" label="运费/KG" />
              <el-table-column prop="OperateFee" label="操作费" />
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="CustomerNames" label="客户" />
        <el-table-column prop="ChannelName" label="渠道" />
        <el-table-column prop="CreateUserName" label="创建用户" />
        <el-table-column prop="CreateTime" label="提交时间" />
        <el-table-column prop="EnableTime" label="生效时间" />
        <el-table-column prop="StatusName" label="状态">
          <template scope="r">
            <el-tag v-if="r.row.Status == 0">审批中</el-tag>
            <el-tag v-else-if="r.row.Status == 1" type="success">已审批</el-tag>
            <el-tag v-else-if="r.row.Status == 2" type="warning">已拒绝</el-tag>
            <el-tag v-else-if="r.row.Status == 3" type="danger">异常</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ProcessMessage" label="处理消息" />
        <el-table-column label="操作" :width="120" fixed="right">
          <template scope="r">
            <div class="action-btn">
              <el-button
                :loading="exportingItem==r.row"
                type="primary"
                size="mini"
                @click="exportQuotation(r.row)"
              >导出报价</el-button>
            </div>
            <div class="action-btn">
              <el-button
                :loading="r.row.detailLoading"
                v-if="getCurrentUser(r.row.Status, r.row.CustomerNames, r.row.CreateUserName)"
                type="success"
                size="mini"
                @click="approvedQuotation(r.row)"
              >手动重试通过</el-button>
            </div>
            <div>
              <el-button
                :loading="r.row.errorLoading"
                v-if="getCurrentUser(r.row.Status, r.row.CustomerNames, r.row.CreateUserName)"
                type="warning"
                size="mini"
                @click="rejectQuotation(r.row)"
              >驳回</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :page-sizes="[10, 20, 40, 100, 400]"
        :current-page="pagerDto.PageIndex"
        :page-size.sync="pagerDto.PageSize"
        background
        layout="prev, pager, next ,total ,jumper,sizes,slot "
        :total="pagerDto.total"
        @size-change="changePager"
        @current-change="pagerSerach"
      />
    </template>
  </base-list>
</template>
<script>
import BaseList from '@/components/Xyy/baselist'
import { _getAllUsers, _getCustomers, _getPublicChannel } from '@/api/baseInfo'
import { exportZipFile } from '@/utils/filedown'
import { _queryPage, _getDetails, _export, _handleQuotationApproved, _newHandleQuotationApproved, _handleQuotationReject } from '@/api/quotationApprove'
import { mapGetters } from 'vuex';
export default {
  name: 'QuotationApproveRecord',
  components: { 'base-list': BaseList },
  data() {
    return {
      showDetail: false,
      exportingItem: null,
      loadingDetails: false,
      multipleSelection: [],
      Statuses: [
        { Name: '未审核', Id: 0 },
        { Name: '已审核', Id: 1 },
        { Name: '已拒绝', Id: 2 },
        { Name: '异常', Id: 3 }
      ],
      customers: [],
      publicChannels: [],
      data: [],
      dataLoading: false,
      pagerDto: {
        _GrE_CreateTime: null,
        PageIndex: 0,
        PageSize: 10,
        total: 0
      },
      users: [],
      selectList: [],
      exportLoading: false,
      batchLoading: false,
      dingdingProcessIdList: []
    }
  },
  computed: {
    ...mapGetters(['introduction', 'roles']),
    // 用户id
    getUsersBtn() {
      // (1：管理员) (杨福全)： 137 ， 肖灿丽,冯珊珊： 347、1023 徐俊峰： 1046
      const userid1 = [137]
      if(userid1.indexOf(this.introduction) !== -1) return 'branchUser'
      const userid2 = [1046]
      if(userid2.indexOf(this.introduction) !== -1) return 'xuJunfengUser'
      const userid3 = [347, 1023, 1723]
      if(userid3.indexOf(this.introduction) !== -1) return 'customersUser'
    },
    getAdminRoles() {
      if(this.roles.length === 0) return false
      return this.roles.some((item) => item.includes('系统管理员') || item.includes('财务'))
    },
  },
  created(){
    _getCustomers().then((response) => {
      this.customers = response
    })
    _getPublicChannel().then((resp) => {
      this.publicChannels = resp
    })
    _getAllUsers().then((resp) => {
      this.users = resp
    })
    this.pagerDto._GrE_CreateTime = this.getLastWeekDate()
  },
  mounted() {
    this.pagerSerach(1)
  },
  methods: {
    exportQuotation(row) {
      const customerIds = row.CustomerIds
      this.exportingItem = row
      _export(customerIds, row.EnableTime).then((res) => {
        // console.log(res)
        this.exportingItem = null
        exportZipFile(res)
      }).finally(() => {
        this.exportingItem = null
      })
    },
    approvedQuotation(row) {
      const that = this
      that.$confirm('是否确认通过').then(r => {
        that.$set(row, 'detailLoading', true)
        _handleQuotationApproved(row.DingdingProcessId).then(y => {
          that.pagerSerach(1)
        }).finally(() => {
          that.$set(row, 'detailLoading', false)
          // if(!row.detailLoading) delete row.detailLoading
        })
      })
    },
    // 驳回
    rejectQuotation(row) {
      const that = this
      that.$confirm('是否确认驳回').then(r => {
        that.$set(row, 'errorLoading', true)
        _handleQuotationReject(row.DingdingProcessId).then(y => {
          that.pagerSerach(1)
        }).finally(() => {
          that.$set(row, 'errorLoading', false)
        })
      })
    },
    expandChange(row, expandedRows) {
      if (expandedRows && expandedRows.length > 0) {
        row.LoadingDetails = true
        this.viewDetail(row)
      }
    },
    viewDetail(item) {
      const id = item.Id
      _getDetails(id).then((res) => {
        item.Details = res
        debugger
        if(item.Remark=='折扣'){
          item.Details.forEach(element => {
            try{
              element.OperateFee = this.customers.filter((x)=>x.Id==element.OperateFee)[0].CompanyName
            }catch{

            }
          });
        }
        item.LoadingDetails = false
      })
    },
    pagerSerach(index) {
      this.dataLoading = true
      if (index) {
        this.pagerDto.PageIndex = index
      }

      _queryPage(this.pagerDto)
        .then((res) => {
          // console.log(res)
          this.data = res.Result
          this.pagerDto.total = res.TotalCount
        })
        .finally((res) => {
          this.dataLoading = false
        })
    },
    changePager(v) {
      this.PageSize = v
      this.pagerSerach()
    },
    // 对应客户显示按钮操作
    getCurrentUser(status, customerNames, createUserName) {
      // 已审批状态不显示
      if(status === 1) return false
      // 涉及三个分公司客户：137， 其他客户：347、1023
      const companyArr = ['广州分公司','深圳分公司','郑州分公司', '杭州分公司','邮政公开价']
      const customerArr = customerNames.split(',')
      let isSome = false
      if(customerArr.length > 0) {
        isSome = companyArr.some((text) =>
          customerArr.some((itext) => itext === text)
        )
      }
      switch (this.getUsersBtn) {
        case 'branchUser':
          return isSome
        case 'customersUser':
          return !isSome
        case 'xuJunfengUser':
          const isUserShow = createUserName === '郑曼媛' ? true : false
          return isUserShow
        default:
          return false
      }
    },
    // 当前的上一个星期
    getLastWeekDate() {
      const currentDate = new Date();
      // 往前推一个星期
      currentDate.setDate(currentDate.getDate() - 7);
      // 格式化时间为 yyyy-MM-dd 格式
      const formattedDate = currentDate.getFullYear() + '-' + this.addLeadingZero(currentDate.getMonth() + 1) + '-' + this.addLeadingZero(currentDate.getDate());
      return formattedDate
    },
    addLeadingZero(number) {
      return number < 10 ? '0' + number : number;
    },
    // 表格复选框
    handleSelectionChange(list) {
      if(list.length === 0) return
      this.selectList = list.map((item) => item.CustomerIds)
      this.dingdingProcessIdList = list
    },
    // 导出
    exportRecord() {
      if(!this.pagerDto._Eq_EnableTime) {
        this.$message({
          message: '生效时间不能为空！',
          type: 'warning'
        })
        return
      }
      if(this.selectList.length === 0) {
        this.$message({
          message: '请勾选导出的内容！',
          type: 'warning'
        })
        return
      }
      // 扁平化、去重
      const list = this.selectList.flat(1)
      const duplicateList = [...new Set(list)]
      this.exportLoading = true
      _export(duplicateList, this.pagerDto._Eq_EnableTime).then((res) => {
        exportZipFile(res)
      }).finally(() => {
        this.exportLoading = false
      })
    },
    // 批量审批
    batchApproval() {
      const that = this
      if(that.dingdingProcessIdList.length === 0) {
        that.$message({
          message: '请勾选审批的内容！',
          type: 'warning'
        })
        return
      }
      that.$confirm('是否批量审批通过？').then(r => {
        that.batchQuotationReject()
      })
    },
    async batchQuotationReject() {
      const that = this
      that.batchLoading = true
      try {
        for await (let item of that.dingdingProcessIdList) {
          try {
            await _newHandleQuotationApproved(item.DingdingProcessId);
          } catch (error) {
            console.error(`Error processing ${item.DingdingProcessId}:`, error);
          }
        }
      } catch (error) {
      } finally {
        that.batchLoading = false
      }
      that.$message({ message: '操作成功', type: 'success' })
      that.pagerSerach()
    }
  }
}
</script>
<style scoped>
.detail-head {
  background-color: rgb(39, 121, 192);
}
.item-form {
  width: 178px;
}
.action-btn {
  margin-bottom: 5px;
}
</style>
