<!--
    desperation：众包代表任务结算
    date：11-30
-->
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page="pageTask"
        :data="tableDataTask"
        :table-loading="tableLoadingTask"
        @selection-change="selectionChange"
        :selectable="selectable"
        :option="tableOptionTask"
        @on-load="getListTask"
        @search-change="searchChangeTask"
        @refresh-change="refreshChangeTask"
        @size-change="sizeChangeTask"
        @current-change="currentChangeTask"
        @cell-click="editBtns"
      >
        <template slot="menuLeft">
          <!-- <el-button type="primary"   @click="mobile()" :loading="infoExportAllLoading">短信<i class="el-icon-download el-icon--right"></i></el-button> -->
          <el-button type="primary" @click="settle" :loading="settleLoading"
            >结算<i class="el-icon-download el-icon--right"></i
          ></el-button>
        </template>

        <!-- <template slot="menu" slot-scope="scope">
          <el-button
            type="text"
            size="small"
            icon="el-icon-check"
            :disabled="scope.row.ysh <= 0"
            @click="showExportDia(scope.row, scope.index)"
            >导出
          </el-button>
        </template> -->
      </avue-crud>
    </basic-container>

    <el-dialog
      :title="showTitle"
      center
      :visible.sync="showData"
      width="50%"
      :before-close="handleClose"
    >
      <div>
        <el-form ref="form" :model="form" :rules="rules" label-width="150px">
          <el-form-item label="折扣" prop="discount" v-show="showDiscount">
            <el-input
              style="width: 300px"
              @change="$forceUpdate()"
              :disabled="!showSettleAmount"
              v-model="form.discount"
              @input="formatData(form.discount)"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="实际结算金额"
            prop="settleAmount"
            v-show="showDiscount"
          >
            <el-input
              style="width: 300px"
              @change="$forceUpdate()"
              :disabled="showSettleAmount"
              v-model="form.settleAmount"
              @input="formatData2(form.settleAmount)"
            ></el-input>
          </el-form-item>

          <el-form-item
            label="发票类目"
            prop="invoiceCategory"
            v-show="showInvoiceCategory"
          >
            <el-select
              style="width: 300px"
              v-model="form.invoiceCategory"
              placeholder="请选择"
            >
              <el-option
                v-for="item in invoiceVal"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelBtn">取 消</el-button>
        <el-button type="primary" @click="surBtn2()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  taskExportZbbg,
  taskExportZbqybgInfo,
  infoExportJsInfo
} from "@/api/wmtask";
import { tableOptionT_JXS } from "@/const/crud/export";
import {
  selectWmScorePackageList,
  mobile,
  updateById,
  invoiceCategory,
  saveSettleInfo,
  updateByIdWithType
} from "@/api/sysExport";

import { tableOptionTaskZbSettle } from "@/const/crud/export";
import { mapGetters } from "vuex";
import Config from "@/settings";

export default {
  name: "wmtask",
  data() {
    return {
      rules: {},
      taskExportJsLoading: false,
      infoExportAllLoading: false,
      settleLoading: false,
      taskExportLoading: false,
      taskExportInfoLoading: false,
      infoExportLoading: false,
      // centerDialogVisible:false,
      checkRow: null,
      entLevel: 0,
      packageIds: "",
      isAllCheck: false,
      rateForm: {
        socreShtgRate: 0,
        socreYtj: 0,
        socreYjwc: 0,
        dqyyjfzz: 0
      },
      roleSubmitType: true,
      roleAudioType: true,
      map: null,
      getAddress: null,
      getAddCode: null,
      addressKeyword: "",
      shopInfo: {
        lng: null,
        lat: null
      },
      city: "请选择区域",
      addInp: false,
      mask: false,
      searchForm: {},
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOptionT_JXS,

      isHasAudit: false,
      formTask: {},
      searchFormTask: {},
      tableDataTask: [],
      pageTask: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoadingTask: false,
      tableOptionTask: tableOptionTaskZbSettle,

      // 新加的字段
      formType: "",
      showTitle: "",
      rowData: {},
      columnData: {},
      invoiceVal: [
        {
          label: "现代服务*技术咨询服务费",
          value: 3
        },
        {
          label: "现代服务*推广服务费",
          value: 7
        },
        {
          label: "现代服务*其他咨询服务费",
          value: 4
        },
        {
          label: "现代服务*现场辅助服务费",
          value: 5
        }
      ],
      selectionVals: [],
      showData: false,
      showDiscount: false,
      showSettleAmount: false,
      showInvoiceCategory: false,
      invoiceCategoryId: "",
      invoiceCategoryValue: "",
      selectionVal: "",
      form: {
        discount: "",
        settleAmount: "",
        invoiceCategory: ""
      }
    };
  },
  created() {
    // this.invoiceData();
  },
  computed: {
    ...mapGetters(["permissions", "userInfo"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.admin_wmtask_add, false),
        delBtn: this.vaildData(this.permissions.admin_wmtask_del, false),
        editBtn: this.vaildData(this.permissions.admin_wmtask_edit, false)
      };
    }
  },

  methods: {
    // 表格编辑 - 判断折扣和实际结算的显隐dialog
    editBtns(row, column, cell, event) {
      this.rowData = Object.assign({}, row); //tags是所编辑本行内数据对象
      this.showData = true; // 弹出框

      if (
        this.rowData.settleStatus == "1" ||
        this.rowData.settleStatus == "3"
      ) {
        // 结算成功便不能再修改
        this.showData = false;
      } else if (column.property == "discount") {
        this.rules = {
          discount: [{ required: true, message: "请填写折扣", trigger: "blur" }]
        };
        this.formType = "1";
        this.showTitle = "折扣";
        this.showDiscount = true; // 展示 折扣 的输入框
        this.showSettleAmount = true;
        this.form.discount = this.rowData.discount; // 回显值
        this.form.settleAmount = this.rowData.settleAmount;
      } else if (column.property == "settleAmount") {
        this.rules = {
          settleAmount: [
            { required: true, message: "请填写实际结算金额", trigger: "blur" }
          ]
        };
        this.formType = "2";
        this.showTitle = "实际结算金额";
        this.showDiscount = true;
        this.showSettleAmount = false;
        this.form.discount = this.rowData.discount;
        this.form.settleAmount = this.rowData.settleAmount; // 回显值
      } else if (column.property == "invoiceCategory") {
        this.rules = {
          invoiceCategory: [
            { required: true, message: "请选择发票类目", trigger: "change" }
          ]
        };
        this.formType = "3";
        this.showTitle = "发票类目";
        this.showInvoiceCategory = true;
        if (this.rowData.invoiceCategory) {
          this.form.invoiceCategory = this.rowData.invoiceCategory; // 回显值
        }
      } else {
        this.showData = false;
      }
    },
    // 调select的接口
    // invoiceData() {
    //     // 传参
    //     let args = {}
    //     // 请求接口
    //     invoiceCategory(args).then(response => {
    //         this.invoiceVal = response.data.data;
    //     }).catch(() => {
    //         this.showData = false;
    //     })
    // },
    formatData(value) {
      if (value) {
        value = value.replace(/[^\d.\-]/g, ""); //清除"数字"和"." "-"负号以外的字符
        // value = value.replace(/^\./g,""); //验证第一个字符是数字
        value = value.replace(/\.{2,}/g, ""); //只保留第一个, 清除多余的
        value = value
          .replace(".", "$#$")
          .replace(/\./g, "")
          .replace("$#$", ".");
        value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数

        this.form.discount = value;
        this.form.settleAmount = (
          parseFloat(this.rowData.score) * parseFloat(value)
        ).toFixed(2);
      } else {
        this.form.discount = "";
        this.form.settleAmount = "";
      }
    },
    formatData2(value) {
      if (value) {
        value = value.replace(/[^\d.\-]/g, ""); //清除"数字"和"." "-"负号以外的字符
        // value = value.replace(/^\./g,""); //验证第一个字符是数字
        value = value.replace(/\.{2,}/g, ""); //只保留第一个, 清除多余的
        value = value
          .replace(".", "$#$")
          .replace(/\./g, "")
          .replace("$#$", ".");
        value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能输入两个小数
        this.form.settleAmount = value;
        this.form.discount = (
          parseFloat(value) / parseFloat(this.rowData.score)
        ).toFixed(2);
      } else {
        this.form.discount = "";
        this.form.settleAmount = "";
      }
    },

    surBtn2() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let args = {
            id: this.rowData.id
          };
          if (this.showInvoiceCategory) {
            args.formType = this.formType;
            args.invoiceCategory = this.form.invoiceCategory;
          }
          if (this.formType === "1") {
            args.formType = this.formType;
            args.discount = this.form.discount;
            args.score = this.rowData.score;
          }
          if (this.formType === "2") {
            args.formType = this.formType;
            args.settleAmount = this.form.settleAmount;
            args.score = this.rowData.score;
          }
          updateByIdWithType(args)
            .then(response => {
              this.hideDialog();
              this.$message.success("修改成功");
              this.getListTask(this.pageTask);
            })
            .catch(() => {
              this.hideDialog();
            });
        } else {
        }
      });
    },
    hideDialog() {
      this.showData = false;
      this.showSettleAmount = false;
      this.showDiscount = false;
      this.showInvoiceCategory = false;
      this.form = {
        discount: "",
        settleAmount: "",
        invoiceCategory: ""
      };
      this.$refs.form.resetFields();
    },
    // 取消按钮
    cancelBtn() {
      this.hideDialog();
    },
    // 按esc取消
    handleClose(done) {
      done();
      this.hideDialog();
    },

    selectable(row, index) {
      if (row.ysh > 0) {
        return true;
      }
      return false;
    },
    sizeChangeTask(pageSize) {
      this.pageTask.pageSize = pageSize;
    },
    currentChangeTask(current) {
      this.pageTask.currentPage = current;
    },
    searchChangeTask(form, done) {
      this.searchFormTask = form;
      this.pageTask.currentPage = 1;
      this.getListTask(this.pageTask, form);
      done();
    },
    // mobile() {
    //   this.tableLoadingTask = true
    //   this.searchFormTask.typeid=4;

    //   mobile('').then(response => {
    //     this.tableDataTask = response.data.data.records
    //     this.pageTask.total = response.data.data.total
    //     this.tableLoadingTask = false
    //   }).catch(() => {
    //     this.tableLoadingTask=false
    //   })
    // },

    refreshChangeTask() {
      this.getListTask(this.pageTask);
    },
    getListTask(page, params) {
      this.tableLoadingTask = true;
      this.searchFormTask.typeid = 4;

      selectWmScorePackageList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize
          },
          params,
          this.searchFormTask
        )
      )
        .then(response => {
          this.tableDataTask = response.data.data.records;
          this.pageTask.total = response.data.data.total;
          this.tableLoadingTask = false;
        })
        .catch(() => {
          this.tableLoadingTask = false;
        });
    },
    showTaskInfo(row, index) {
      window.open(
        Config.outsideUrl + "/h5/#/pages/task/task-detail/index?id=" + row.id,
        "newwindow",
        "height=750, width=400, top=200, left=300, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no"
      );
    },
    // showExportDia(row, index){
    //   this.checkRow=row;
    //   this.centerDialogVisible=true;
    //   this.isAllCheck=false;
    // },
    taskExport() {
      this.taskExportLoading = true;
      let rowid = "";
      if (this.isAllCheck) {
        rowid = this.packageIds;
      } else {
        let row = this.checkRow;
        rowid = row.id;
      }
      var obj = {
        scorePackageDrugId: rowid
      };
      taskExportZbbg(obj)
        .then(response => {
          if (undefined == response.data || undefined == response.data.data) {
            this.$message.error("导出失败");
            return false;
          }
          let obj = response.data.data;
          let a = document.createElement("a");
          a.href = obj.url; // 这里的请求方式为get，如果需要认证，接口上需要带上token
          a.click();
          this.$message.success("导出众包代表业绩报告成功");
          this.taskExportLoading = false;
        })
        .catch(e => {
          this.taskExportLoading = false;
        });
    },
    taskExportInfo() {
      this.taskExportInfoLoading = true;
      let rowid = "";
      if (this.isAllCheck) {
        rowid = this.packageIds;
      } else {
        let row = this.checkRow;
        rowid = row.id;
      }
      var obj = {
        scorePackageDrugId: rowid
      };
      taskExportZbqybgInfo(obj).then(response => {
        if (undefined == response.data || undefined == response.data.data) {
          this.$message.error("导出失败");
          return false;
        }
        let obj = response.data.data;
        let a = document.createElement("a");
        a.href = obj.url; // 这里的请求方式为get，如果需要认证，接口上需要带上token
        a.click();
        this.taskExportInfoLoading = false;
      });
    },
    taskExportJS() {
      this.taskExportJsLoading = true;
      let rowid = "";
      if (this.isAllCheck) {
        rowid = this.packageIds;
      } else {
        let row = this.checkRow;
        rowid = row.id;
      }
      var obj = {
        scorePackageDrugId: rowid
      };
      infoExportJsInfo(obj)
        .then(response => {
          if (undefined == response.data || undefined == response.data.data) {
            this.$message.error("导出失败");
            return false;
          }
          let obj = response.data.data;
          let a = document.createElement("a");
          a.href = obj.url; // 这里的请求方式为get，如果需要认证，接口上需要带上token
          a.click();
          this.$message.success("导出众包代表业绩报告-结算表成功");
          this.taskExportJsLoading = false;
        })
        .catch(() => {
          this.taskExportJsLoading = false;
        });
    },

    // 结算按钮
    settle() {
      // this.isAllCheck=false;
      // this.centerDialogVisible=true;

      this.settleLoading = true; // 屏蔽结算按钮
      this.tableLoadingTask = true; // 转圈加载
      if ("" == this.packageIds) {
        this.$message.error("请选择需要结算的列");
        this.tableLoadingTask = false;
        this.settleLoading = false; // 转圈加载
        return false;
      }
      //  传参
      let args = this.selectionVals;
      // 请求接口
      saveSettleInfo(args)
        .then(response => {
          this.settleLoading = false; // 转圈加载
          this.tableLoadingTask = false; // 隐藏转圈
          if (response.data.code == "0") {
            this.getListTask(this.pageTask);
            this.$message.warning(response.data.msg);
          } else {
            this.$message.error(response.data.msg);
          }
        })
        .catch(() => {
          this.tableLoadingTask = false;
          this.settleLoading = false; // 转圈加载
          this.showData = false;
        });
    },

    // 选复选框
    selectionChange(selection) {
      this.isHasAudit = false;
      this.packageIds = "";

      if (undefined != selection) {
        for (var i = 0; i < selection.length; i++) {
          if (selection[i].ysh > 0) {
            this.isHasAudit = true;
          }

          this.packageIds += selection[i].id;
          if (i < selection.length - 1) {
            this.packageIds += ",";
          }

          if (selection[i].discount == null) {
            this.getListTask(this.pageTask);
            this.$message.error("请填写折扣");
            return false;
          } else if (selection[i].settleAmount == null) {
            this.getListTask(this.pageTask);
            this.$message.error("请填写实际结算金额");
            return false;
          } else if (selection[i].invoiceCategory == null) {
            this.getListTask(this.pageTask);
            this.$message.error("请选择发票类目");
            return false;
          } else {
            this.selectionVals = selection;
          }
        }
      }
    }
  }
};
</script>
