<template>
  <section v-if="detail" id="wage-settlement">
    <section class="left">
      <h3>工资结算</h3> 
      <h4>
        【
        <a :href="orderHref">{{detail.job.title_count}}</a>
        】{{detail.time.month}}工资账单
        <el-tag size="small">{{detail.statusName}}</el-tag>
        <el-tag size="small">{{detail.invoiceName}}</el-tag>
        <el-tag size="small" v-if="detail.is_use_deposit=='1'">使用押金结算</el-tag>
      </h4>
      <section class="container">
        <span class="title">每月薪资：</span>
        ￥{{salary.job_salary}}/月
      </section>
      <section class="container">
        <span class="title">工作周期：</span>
        {{detail.time.start_time | dateFormat}} 至 {{detail.time.end_time | dateFormat}} ({{detail.days}}天)
      </section>
      <section class="container">
        <span class="title">托管金额：</span>
        ￥{{detail.company.company_pay}}
      </section>
      <section v-if="detail.normal_days > 0" class="container">
        <span class="title">正式工资：</span>
        ￥{{salary.normal_salary}}({{detail.normal_days}}天)
      </section>
      <section v-if="detail.probation_days > 0" class="container">
        <span class="title">试用工资：</span>
        ￥{{salary.probation_salary}}({{detail.probation_days}}天，按月工资{{rate.probation_rate}}%结算)
      </section>
      <section class="container">
        <span class="title">结算比例：</span>
        <el-input type="number" v-model="detail.work_hour.work_rate"></el-input>
        % (工作工时：{{detail.work_hour.worked_hours}}/{{detail.work_hour.should_work_hours}})
      </section>
      <section class="container">
        <span class="title">扣减工资：</span>
        <el-input type="number" v-model="salary.deduction_fee"></el-input>元
      </section>
      <section class="container salary-container">
        <span class="title">本月工资：</span>
        <section>
          <div class="salary-result">￥{{baseSalary}}</div>
          <div
            class="salary-calc"
          >=({{salary.normal_salary}}+{{salary.probation_salary}})*{{detail.work_hour.work_rate}}%-{{salary.deduction_fee}}</div>
        </section>
      </section>
      <section class="container">
        <span class="title">平台服务费：</span>
        <el-input type="number" v-model="rate.origin_person_service_fee_rate"></el-input>
        VIP会员减免{{rate.person_service_fee_rate_reduce}}% ￥{{vipMinus}} (开发者服务费率{{devServiceRate}}%)
      </section>
      <section class="container">
        <span class="title">应缴税费：</span>
        <el-checkbox type="checkbox" v-model="dev_is_invoice"></el-checkbox>
        ￥{{shouldRate}} (开发者税率{{devRate}}%)
      </section>
      <section class="container salary-container">
        <span class="title">实际工资：</span>
        <section>
          <div class="salary-result">￥{{personPrice}}</div>
          <div class="salary-calc">
            <span>=(({{salary.normal_salary}}+{{salary.probation_salary}})*{{detail.work_hour.work_rate}}%-{{salary.deduction_fee * 1}})*(1-{{rate.person_service_fee_rate}}%)</span>
            <span
              v-if="dev_is_invoice"
            >*(1-{{rate.person_tax_rate}}%-{{rate.person_tax_service_fee_rate}}%)</span>
          </div>
        </section>
      </section>
      <!-- 本月结束合作，下月未托管费用 -->
      <section v-if="detail.can_use_deposit" class="container">
        <el-checkbox v-model="is_use_deposit" style="margin: 0 4px 0 0;" disabled checked></el-checkbox>
        使用押金结算(￥{{detail.company.company_left_deposit}})(企业方费用：￥{{companyPrice}})
      </section>
      <section class="container">
        <span class="title">退还金额：</span>
        <el-input type="text" :value="returnMoney" disabled></el-input>
        =(({{salary.normal_salary}}+{{salary.probation_salary}})-{{baseSalary}})*(1+{{rate.company_service_fee_rate}}%)
        <span
          v-if="is_invoice"
        >*(1+{{this.is_invoice ? rate.company_tax_rate : 0}}%)</span>元
      </section>
      <section class="container">
        <span class="title">备注说明：</span>
        <el-input v-model="detail.remark"></el-input>
      </section>
      <section class="container">
        <span class="title">提成客户经理</span>
        {{detail.user_manager ? `${detail.user_manager.nickname}(${detail.user_manager.uid})` : ''}}
        <el-button @click="clientChangeDialog = true" type="text">更换</el-button>
        <el-dialog title="更换提成客户经理" :visible.sync="clientChangeDialog" width="30%">
          <div>客户昵称：{{detail.company_info ?`${detail.company_info.nickname}(${detail.company_info.uid})` : ''}}</div>
          <div>
            客户经理：
            <el-select v-model="clientSelected" placeholder="请选择">
              <el-option
                v-for="item in clients"
                :key="item.uid"
                :label="`${item.nickname}(${item.uid})`"
                :value="item.uid"
              ></el-option>
            </el-select>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="clientChangeDialog = false">取 消</el-button>
            <el-button type="primary" @click="handleClientChange">确 定</el-button>
          </span>
        </el-dialog>
      </section>
      <el-button
        v-show="detail.status == 2 || detail.status == 3"
        @click="jobPeriodSettle('save')"
      >保存</el-button>
      <section v-if="detail.can_send_salary" class="container" style="margin-top: 20px;">
        <el-button
          type="primary"
          v-show="detail.status == 3"
          @click="jobPeriodSettle('confirm')"
        >确定支付工资</el-button>
      </section>
    </section>
    <section class="right">
      <textarea v-model="remind" placeholder="请输入备注" maxlength="200"></textarea>
      <el-button style="width: 100px;" @click="clickRemindSave" type="primary">保存</el-button>
      <section class="reminds">
        <section class="remind" v-for="remind of reminds" :key="remind.id">
          <img class="remind-head" :src="remind.icon_url" alt="icon" />
          <section class="remind-right">
            <section class="remind-top">
              <span class="remind-nickname">{{remind.nickname}}</span>
              <span class="remind-date">{{remind.create_date}}</span>
            </section>
            <p class="remind-content">{{remind.content}}</p>
          </section>
        </section>
      </section>
      <el-pagination
        layout="prev, pager, next"
        :total="total"
        :page-size="20"
        @current-change="changePagination"
      ></el-pagination>
    </section>
  </section>
</template>

<script>
// 现在环境是线上还是测试, 默认线上
let env = ''
// 备注页码
let currentPage = 1

export default {
  data() {
    return {
      // 全部备注数量
      total: 0,
      // 历史备注
      reminds: [],
      // 备注信息
      remind: '',
      job_id: '',
      period_id: '',
      is_invoice: false,
      dev_is_invoice: false,
      is_use_deposit: false,
      detail: null,
      clientChangeDialog: false,
      clients: [],
      clientSelected: ''
    }
  },
  computed: {
    /**
     * 详情链接地址
     */
    orderHref() {
      let detail = this.detail
        , hrefFix = `/rooter/cloudjobitem/${detail.job_id}`
      if (env === 'test') hrefFix = `https://dev.test.proginn.com${hrefFix}`
      else hrefFix = `https://www.proginn.com${hrefFix}`
      return hrefFix
    },
    /**
     * 开发者服务费率
     */
    devServiceRate() {
      let rate = this.rate
      let result = +rate.origin_person_service_fee_rate - +rate.person_service_fee_rate_reduce
      return result < 0 ? 0 : result
    },
    /**
     * 开发者税率
     */
    devRate() {
      let rate = this.rate
      return +rate.person_tax_rate + +rate.person_tax_service_fee_rate
    },
    /**
     * 薪资
     */
    salary() {
      return this.detail.salary
    },
    /**
     * 会员减免
     */
    vipMinus() {
      let salary = this.salary
      let rate = this.rate
      return this.keepDecimal(((salary.normal_salary * 1 + salary.probation_salary * 1) * (this.detail.work_hour.work_rate / 100) - salary.deduction_fee * 1) * ((rate.origin_person_service_fee_rate - rate.person_service_fee_rate_reduce) / 100))
    },
    /**
     * 税率
     */
    rate() {
      return this.detail.rate
    },
    /**
     * 应缴税费
     */
    shouldRate() {
      let rate = this.rate
      return this.keepDecimal(+this.baseSalary * (1 - +rate.origin_person_service_fee_rate / 100 + +rate.person_service_fee_rate_reduce / 100) * this.devRate / 100)
    },
    /**
     * 本月工资
     */
    baseSalary() {
      let salary = this.salary
      return this.keepDecimal((+salary.normal_salary + +salary.probation_salary) * +this.detail.work_hour.work_rate / 100 - +salary.deduction_fee)
    },
    /**
     * 退还金额
     */
    returnMoney() {
      if (this.is_use_deposit) return 0

      let salary = this.salary
      let isPay = +this.detail.company.company_pay > 0 ? 1 : 0
      let hasTax = this.detail.is_invoice == '1' ? (1 + +this.detail.rate.company_tax_rate / 100) : 1
      return this.keepDecimal((+salary.normal_salary + +salary.probation_salary - +this.baseSalary) * (1 + +this.detail.rate.company_service_fee_rate / 100) * hasTax) * isPay
    },
    /**
     * 实际工资
     */
    personPrice() {
      let salary = this.salary
      let rate = this.detail.rate
      let work_hour = this.detail.work_hour
      let isPayable = this.dev_is_invoice ? (1 - rate.person_tax_rate / 100 - rate.person_tax_service_fee_rate / 100) : 1
      let personPrice = (((salary.normal_salary - 0) + (salary.probation_salary - 0)) * work_hour.work_rate / 100 - +salary.deduction_fee) * (1 - rate.person_service_fee_rate / 100) * isPayable

      return this.keepDecimal(personPrice)
    },
    /**
     * 企业方费用
     */
    companyPrice() {
      let salary = this.salary
      let rate = this.detail.rate
      let work_hour = this.detail.work_hour
      let isPayable = this.is_invoice ? (1 + rate.company_tax_rate / 100) : 1
      let companyPrice = (((salary.normal_salary - 0) + (salary.probation_salary - 0)) * work_hour.work_rate / 100 - +salary.deduction_fee) * (1 + rate.company_service_fee_rate / 100) * isPayable
      return this.keepDecimal(companyPrice)
    },
    /**
     * is_invoice根据身份取值
     */
    isInvoice() {
      return this.detail[this.isDev ? 'dev_is_invoice' : 'is_invoice']
    }
  },
  filters: {
    /**
     * 格式化日期
     */
    dateFormat(val) {
      return new Date(+val * 1000).toLocaleDateString()
    }
  },
  mounted() {
    this.job_id = this.$route.query.job_id
    this.period_id = this.$route.query.period_id
    this.getClients();
    this.getData()
    this.getReminds()
  },
  methods: {
    /**
     * 备注页码变化
     */
    changePagination(page) {
      this.getReminds(page)
    },
    async getReminds(page = currentPage) {
      this.reminds = []
      let { status, data } = await this.$post('/api/admin/job/getPeriodNote', { period_id: this.period_id, page })
      currentPage = page
      console.log(data)
      if (status) {
        this.total = data.total
        this.reminds = data.list
      }
    },
    /**
     * 点击提交备注
     */
    async clickRemindSave() {
      console.log(this.remind)
      if (!this.remind.length) {
        this.$message({
          message: '请输入备注',
          type: 'warning'
        })
        return
      }
      let content = `${this.remind} -账单ID${this.period_id}`
      let res = await this.$post('/api/admin/job/note', { id: this.job_id, period_id: this.period_id, content })
      console.log(res)
      if (res.status) {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
        setTimeout(() => {
          location.reload()
        }, 1500);
      } else {
        this.$message({
          message: '保存失败',
          type: 'error'
        })
      }
    },
    /**
     * 有效数字控制
     */
    keepDecimal(num) {
      return num.toFixed(2)
    },
    /**
     * 点击保存或支付
     */
    async jobPeriodSettle(action) {
      if (this.returnMoney < 0 || this.detail.work_hour.work_rate > 100) {
        this.$message({
          message: '退还金额不能小于0 且 结算比例不能大于100',
          type: 'error'
        })
        return;
      }
      let body = {
        // 云端工作周期id(int)
        period_id: this.period_id,
        // 云端工作id（int）
        job_id: this.job_id,
        // 操作名称 save-保存结算信息 confirm-确认支付工资
        action,
        // 结算比例（百分比）
        work_rate: this.detail.work_hour.work_rate,
        // 扣减工资（数值，两位小数）
        deduction_fee: this.salary.deduction_fee,
        // 退还金额（数值，两位小数）
        return_money: this.returnMoney,
        // 结算工资时的备注（可选）
        remark: this.detail.remark,
        // 结算时是否使用押金
        is_use_deposit: this.is_use_deposit ? 1 : 0,
        person_service_fee_rate: this.detail.rate.origin_person_service_fee_rate,
      }
      body.dev_is_invoice = this.dev_is_invoice ? 1 : 0

      let res = await this.$post('/api/admin/job/job_period_settle', body)
      if (!res) return
      if (res.status > 0) {
        this.$message({
          message: res.info,
          type: 'success'
        });
        setTimeout(() => {
          location.reload()
        }, 1000)
      } else {
        if (!res.info) {
          console.log(res)
        }
        this.$message({
          message: res.info ? res.info : '接口返回数据异常',
          type: 'error'
        })
      }
    },
    /**
     * 获取数据
     */
    async getData(i) {
      let res = await this.$post('/api/admin/job/get_job_period_detail', {
        job_id: this.job_id,
        period_id: this.period_id,
        is_cal_workrate: 1
      })
      if (!res.data) return
      let data = res.data
      env = data.current_env
      this.detail = data
      this.isDev = data.is_dev
      this.is_invoice = this.detail.is_invoice === '1'
      this.dev_is_invoice = this.detail.dev_is_invoice == '1'
      this.is_use_deposit = data.can_use_deposit === '1'
      this.clientSelected = this.detail.user_manager ? this.detail.user_manager.uid : '';
    },
    /**
     * 获取客户经理
     */
    async getClients() {
      let res = await this.$post('/api/admin/user_manager/get_manager', {
      })
      if (!res.data) return
      let data = res.data
      console.log(data)
      this.clients = data.managers
    },
    /**
     * 更换客户经理
     */
    async handleClientChange() {
      if (!this.clientSelected) {
        this.$message.error('请选择客户经理');
      }
      let res = await this.$post('/api/admin/user_manager/change_manager_record', {
        manager_id: this.clientSelected,
        period_id: this.period_id,
      })
      if (res.status === 1) {
        this.$message({
          message: '修改成功',
          type: 'success'
        })
        this.getData();
        this.clientSelected = '';
        this.clientChangeDialog = false;
      } else {
        this.$message.error('修改失败！' + res.info)
      }
    }
  }
}
</script>

<style scoped>
#wage-settlement {
  display: flex;
  padding: 20px;
}
.left,
.right {
  flex: 1;
}
.left {
  border-right: 1px solid #ccc;
  padding-right: 20px;
}
.right {
  padding: 20px;
}
.container {
  display: flex;
  align-items: center;
  height: 44px;
}
.salary-container {
  height: 80px;
  background: #f0f0f0;
}
.salary-result {
  font-size: 28px;
  font-weight: 800;
}
.salary-calc {
  color: #666;
  margin-left: 40px;
}
.title {
  width: 120px;
}
.el-input {
  width: 180px;
}
textarea {
  resize: none;
  width: 100%;
  height: 120px;
  padding: 12px;
}
.reminds {
  margin-top: 40px;
  height: 600px;
  overflow-y: scroll;
}
.remind {
  display: flex;
  margin-bottom: 40px;
}
.remind-head {
  --width: 40px;
  width: var(--width);
  height: var(--width);
  border-radius: 50%;
  margin-right: 10px;
}
.remind-right {
  display: flex;
  flex-direction: column;
}
.remind-nickname {
  font-weight: 800;
}
.remind-date {
  color: #999;
}
.remind-content {
  border-left: 4px solid #d8d8d8;
  padding-left: 10px;
  margin-top: 10px;
}
</style>
