<template>
  <el-dialog :close-on-click-modal="false" v-dialogDrag :title="title" :visible.sync="detailDialog" width="80%" append-to-body :before-close="handleClose">
    <el-table 
    :data="form.courseLists" 
    :header-cell-style="{
      background: 'linear-gradient(#6cb3ff, #1873d4)',
      color: '#eeeeee'
    }" >
      <el-table-column align="center" prop="courseReatmentNum" label="单号" min-width="130"></el-table-column>
      <el-table-column align="center" prop="date" label="单据日期" min-width="150"> </el-table-column>
      <el-table-column align="center" prop="memberName" label="名字" min-width="70"> </el-table-column>
      <el-table-column align="center" prop="mobilePhone" label="手机号码" min-width="100"> </el-table-column>
      <el-table-column align="center" prop="projectNum" label="疗程编码" min-width="100"> </el-table-column>
      <el-table-column align="center" prop="projectName" label="疗程名称" min-width="100"> </el-table-column>
      <el-table-column align="center" prop="priceMember" label="单价" min-width="80"> </el-table-column>
      <el-table-column align="center" prop="salesPrice" label="成交单价" min-width="80"> </el-table-column>
      <el-table-column align="center" prop="numberTimes" label="购买次数" min-width="80"> </el-table-column>
      <el-table-column align="center" prop="amount" label="成交金额" min-width="80"> </el-table-column>
      <el-table-column align="center" prop="debtMoney" label="待付金额" min-width="80"> </el-table-column>
      <el-table-column align="center" prop="courseReatmentAmount" label="实付金额" min-width="100">
        <template slot-scope="scope">
          {{ scope.row.amount - scope.row.debtMoney }}
        </template>  
      </el-table-column>
      <el-table-column align="center" prop="description" label="说明" min-width="120"> </el-table-column>
      <el-table-column show-overflow-tooltip min-width="100" align="center" label="提成明细">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleCommission(scope.row)">明细</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="text-bold padding-xs">卡付/现付</div>
      <div class="flex justify-start align-start ">
        <div style="width: 590px" class="border-radius-10 border margin-right-xs  bg-white padding-xs" v-if="sessionStorageData.refillCard">
          <el-table :data="form.rechargeConsumeList" style="width: 590px" :summary-method="getSummaries" show-summary>
            <el-table-column align="center" prop="rechargeTypeName" label="名称" min-width="120"></el-table-column>
            <el-table-column align="center" prop="cardOver" label="可用金额" width="90"></el-table-column>
            <el-table-column align="center" prop="spendMoney" label="本次支付" width="100"></el-table-column>
            <el-table-column align="center" prop="cardOvers" label="可用余额" width="90"></el-table-column>
          </el-table>
        </div>
        <div style="width: 280px" class="border-radius-10 border margin-right-xs  bg-white padding-xs">
          <el-table :data="form.payLists" :summary-method="getSummaries" show-summary>
            <el-table-column align="center" prop="payId" label="支付方式" min-width="100">
              <template slot-scope="scope">
                <el-select v-model="scope.row.payId" placeholder="请选择">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="payMoney" label="支付金额" min-width="120"> </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- </el-collapse-item> -->
      <div class="text-bold padding-xs">员工/门店管理层/高管业绩</div>
      <div class="flex justify-start align-start  flex-wrap ">
        <staffsles ref="staffsles" @staffslesData="staffslesData"></staffsles>
        <admin ref="admin" @adminData="adminData"></admin>
        <manager ref="manager" @managerData="managerData"></manager>
      </div>
    <span slot="footer" class="dialog-footer" v-if="title=='明细'">
      <el-button size="mini" type="primary" @click="detailDialog=false">关闭</el-button>
    </span>
    <span v-else slot="footer" class="dialog-footer">
      <!-- 补单才需要短信重发 -->
      <el-button size="mini" type="primary" @click="handleReissue">短信重发</el-button>
      <el-button size="mini" type="primary" plain @click="cancel()">取 消</el-button>
      <el-button v-if="form.isCancel==0" size="mini" type="primary" @click="subStaffRatio()">修 改</el-button>
    </span>
    <errorOrder ref="detail"></errorOrder>
  </el-dialog>
</template>

<script>
import { courseEditStaff, selectOne, courseReissue,selectCourseOne,ctlist,selectCourseOneByError } from "@/api/eashier.js";
import admin from "@/components/staffList/admin/index";
import manager from "@/components/staffList/manager/index";
import staffsles from "@/components/staffList/staff/index";
import errorOrder from '../../errorOrder/component/index.vue'
export default {
  components: {
    staffsles,
    manager,
    admin,
    errorOrder
  },
  props:{
    isaAbnormal:{
      type:Boolean,
      default:false
    },
    project:{
      type:Object,
      default:()=>{}
    }
  },
  data() {
    return {
      detailDialog: false,
      activeNames: "员工",
      rowfromWidth: "80px",
      sessionStorageData: {}, //门店参数集合
      title: "", //弹窗标题
      form: {}, //主对象
      options:[]
    };
  },
  created(){
    this.init()
  },
  methods: {
    handleCommission(){
        this.$refs.detail.show(this.project)
    },
    init(){
      ctlist({
        state: 1
      }).then(res=>{
        this.options = res.rows.map(item=>{
          return {
            value:item.id,
            label:item.collectionTypeName
          }
        })
      })
    }, 
    handleReissue(){
      let params = {
        additionDate:this.form['courseLists'][0]['date'],
        mobilePhone:this.form['mobilePhone'],
        projectName:this.form['projectName'],
        courseLists:this.form['courseLists']
      }
      courseReissue(params).then(res=>{
        if(res.code === '000000'){
          return this.$message.success({
              message: "操作成功!",
            });
        }else{
          this.$alert(res.message, "提示", {
            confirmButtonText: "确定",
            confirmButtonClass: "confirmbtnFalses",
            type: "warning",
            center: true,
            callback: (action) => {
            },
          });
        }
      })
    },
    //关闭弹窗前的回调方法
    handleClose() {
      this.form = Object.assign({});
      this.detailDialog = false;
    },
    collChange(e) {
      if (e.indexOf("员工")) {
        this.setStaff();
      }
    },
    setStaff() {
      var that = this;
      setTimeout(() => {
        that.$refs.staffsles.show(that.form.entities, that.form.storeId);
        that.$refs.admin.show(that.form.adminList, that.form.storeId);
        that.$refs.manager.show(that.form.managerList, that.form.storeId);
      }, 800);
    },
    //员工占比返回方法
    staffslesData(v) {
      this.form.entities = [...v];
    },
    //高管占比返回方法
    managerData(v) {
      this.form.managerList = [...v];
    },
    //管理员占比返回方法
    adminData(v) {
      this.form.adminList = [...v];
    },
    cancel() {
      this.detailDialog = false;
      this.$emit("detailData");
    },
    //组件传值
    show(form, text) {
      if (text == "明细") {
        this.title = text;
      } else {
        this.title = "明细/修改";
      }
      this.detailDialog = true;
      this.sessionStorageData = JSON.parse(
        sessionStorage.getItem("sessionStorageData")
      );
      this.getData(form);
      form.rechargeConsumeList.forEach((items) => {
        let cardOver = (items.cardConsumeMoney + items.spendMoney).toFixed(2)*1;
        let cardOvers = items.cardConsumeMoney.toFixed(2)*1;
        items.cardOver = cardOver
        items.cardOvers = cardOvers
      });
    },
    getData(row) {
      this.form = {
        ...row,
      };
      this.form.entities.forEach((item) => {
        item.staffName = item.saleStaffName;
        item.editStaffRatioShow = false;
        item.id = item.saleStaffId;
        item.identityCard = item.saleIdentityCard;
        item.ratio = item.saleRatio;
        item.staffNames = item.brandNumber + "--" + item.staffName;
      });
      selectOne({ type: 1, orderId: row.id }).then((res) => {
        if (res.code == "000000") {
          let managerList = [];
          let adminList = [];
          res.rows.forEach((item) => {
            if (item.staffType == 0) {
              item.staffNames = item.brandNumber + "--" + item.staffName;
              managerList.push(item);
            }
            if (item.staffType == 1) {
              item.staffNames = item.brandNumber + "--" + item.staffName;
              adminList.push(item);
            }
          });
          if (managerList.length == 0) {
            managerList.push({ ratio: 100 });
          }
          if (adminList.length == 0) {
            adminList.push({ ratio: 100 });
          }
          if (this.form.entities.length == 0) {
            this.form.entities.push({ ratio: 100 });
          }
          this.form.managerList = managerList;
          this.form.adminList = adminList;
          this.setStaff();
        } else {
          this.$alert(res.message, "加载门店高管", {
            confirmButtonText: "确定",
            confirmButtonClass: "confirmbtnFalses",
            type: "warning",
            center: true,
            callback: (action) => {},
          });
        }
      });
      if(this.isaAbnormal){
        let params = {
          id:this.form.id,
          date:this.form.date
        }
        selectCourseOneByError(params).then(res=>{
          if(res.code == '000000'){
            this.$set(this.form,'courseLists',res.data.courseLists)
          }
        })
      }else{
        let params = {
        docId:this.form.courseReatmentNum,
        date:this.form.date
        }
        selectCourseOne(params).then(res=>{
          if(res.code == '000000'){
              // this.form.courseLists = res.data.courseLists
              this.$set(this.form,'courseLists',res.data.courseLists)
          }
        })
      }
    },
    //指定列求和
    //数组按对应字段合计返回方法
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (column.property == "spendMoney") {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              sums[index] = "--";
            }
          }, 0);
          sums[index] += " ";
        } else if (column.property == "payMoney") {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              sums[index] = "--";
            }
          }, 0);
          sums[index] += " ";
        } else {
          sums[index] = "--";
        }
      });
      return sums;
    },
    subStaffRatio() {
      let staffLists = [];
      this.form.entities.forEach((item) => {
        let items = {
          ratio: item.ratio.toFixed(2)*1,
          id: item.id,
          identityCard: item.identityCard,
          staffName: item.staffName,
          brandNumber: item.brandNumber,
          editStaffRatioShow: false,
        };
        staffLists.push(items);
      });
      let form = {
        date: this.form.date,
        collectionAmount: this.form.collectionAmount,
        typeRatio: this.form.typeRatio,
        id: this.form.id,
        docId: this.form.courseLists[0].courseReatmentNum,
        staffLists: staffLists,
        collectionCashAmount: this.form.collectionCashAmount,
        collectionIntegralAmount: this.form.collectionIntegralAmount,
        collectionRechargeAmount: this.form.collectionRechargeAmount,
        payLists:this.form.payLists
      };
      let salesmens = [];
      this.form.managerList.forEach((item) => {
        if (item.id) {
          item.staffType = 0;
          item.ratio = item.ratio.toFixed(2)*1
          salesmens.push(item);
        }
      });
      this.form.adminList.forEach((item) => {
        if (item.id) {
          item.staffType = 1;
          item.ratio = item.ratio.toFixed(2)*1
          salesmens.push(item);
        }
      });
      form.salesmens = salesmens;
      courseEditStaff(form).then((res) => {
        if (res.code == "000000") {
          this.$message.success({
            message: res.message,
          });
          this.detailDialog = false;
          this.$emit("detailData");
        } else {
          this.$alert(res.message, "提示", {
            confirmButtonText: "确定",
            confirmButtonClass: "confirmbtnFalses",
            type: "warning",
            center: true,
            callback: (action) => {},
          });
        }
      });
    },
  },
};
</script>

<style scoped>
.spanrs{
  width: 160px;
}
</style>
