<template>
  <div class="diagnosis-list-content">
    <div class="select-content screenSet">
      <div class="title">
        服务列表
      </div>
      <el-collapse-transition>
        <div v-show="isUp">
          <el-form
            ref="form"
            :inline="true"
            :model="searchParam"
            label-suffix=":"
            label-width="120px"
            label-position="right"
            style="width: 100%"
          >
            <el-row
              :gutter="30"
              type="flex"
              style="margin-bottom: 0"
            >
              <el-col :span="13">
                <el-form-item label="服务医生">
                  <el-input
                    v-model="searchParam.searchKey"
                    size="middle"
                    placeholder="请输入医生姓名或联系电话"
                    style="width: 120%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="服务名称">
                  <el-select
                    id="statusSelector"
                    v-model="searchParam.serviceTypeId"
                    placeholder="请选择服务名称"
                    clearable
                    style="margin-left: 20px; height: 32px; line-height: 32px"
                  >
                    <el-option
                      v-for="item in serviceTypeList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row
              :gutter="30"
              type="flex"
              style="margin-bottom: 0"
            >
              <el-col :span="13">
                <el-form-item label="创建时间">
                  <el-date-picker
                    v-model="rangeTime"
                    type="daterange"
                    value-format="yyyy-MM-dd"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    style="width: 100%"
                    :picker-options="pickerOptions1"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="状态">
                  <el-select
                    id="statusSelector"
                    v-model="searchParam.status"
                    placeholder="请选择服务状态"
                    clearable
                    style="margin-left: 20px; height: 32px; line-height: 32px"
                  >
                    <el-option
                      v-for="item in statusList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row
              :gutter="30"
              type="flex"
              style="margin-bottom: 0"
            >
              <el-col :span="8">
                <el-form-item label="接诊分佣方式">
                  <el-select
                    id="statusSelector"
                    v-model="searchParam.commissionType"
                    placeholder="请选择服务状态"
                    clearable
                    style="height: 32px; line-height: 32px; width: 100%"
                  >
                    <el-option
                      v-for="item in commissionTypeList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col
                :span="16"
                style="text-align: right; padding-right: 55px"
              >
                <el-button
                  type="primary"
                  size="small"
                  @click="search()"
                >
                  搜索
                </el-button>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-transition>
      <div
        class="select-bottom"
        @click="selectToggle"
      >
        <span v-if="!isUp">展开筛选<i class="el-icon-arrow-down" /></span>
        <span v-else>收起筛选<i class="el-icon-arrow-up" /></span>
      </div>
    </div>
    <div
      id="screenSet"
      class="component-content screenSet"
    >
      <el-row
        :gutter="30"
        type="flex"
        style="margin-bottom: 0; float: right"
      >
        <el-col
          :span="5"
          style="text-align: right; margin-bottom: 10px"
        >
          <el-button
            type="primary"
            size="small"
            @click="refresh()"
          >
            刷新页面
          </el-button>
        </el-col>
        <el-col
          :span="5"
          style="text-align: right"
        >
          <el-button
            type="primary"
            size="small"
            @click="batchOffline()"
          >
            批量下架
          </el-button>
        </el-col>
        <el-col
          :span="5"
          style="text-align: right"
        >
          <el-button
            type="primary"
            size="small"
            @click="batchOnline()"
          >
            批量上架
          </el-button>
        </el-col>
        <el-col
          :span="5"
          style="text-align: right"
        >
          <el-button
            type="primary"
            size="small"
            @click="batchSetPrice()"
          >
            批量设置价格
          </el-button>
        </el-col>
      </el-row>
      <!-- 表格 -->
      <el-table
        v-loading="loading"
        class="search-table"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="50"
        />
        <el-table-column
          prop="id"
          label="ID"
          min-width="50"
          align="left"
        />
        <el-table-column
          prop="serviceName"
          label="服务名称"
          min-width="100"
          align="left"
        />
        <el-table-column
          prop="doctorName"
          label="服务医生"
          min-width="120"
          align="left"
        />
        <el-table-column
          prop="mobilePhone"
          label="联系电话"
          min-width="120"
          align="left"
        />
        <el-table-column
          prop="price"
          label="价格(元)"
          min-width="80"
          align="left"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.price | rounding }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="commissionTypeStr"
          label="接诊分佣方式"
          min-width="120"
          align="left"
        />
        <el-table-column
          prop="commissionFee"
          label="分佣金额（元）"
          min-width="120"
          align="left"
        >
          <!--                      <template slot-scope="scope">-->
          <!--                        <span v-if="scope.row.commissionType == 1">{{scope.row.commissionFee}}%</span>-->
          <!--                        <span v-if="scope.row.commissionType == 2">{{scope.row.commissionFee}}元</span>-->
          <!--                      </template>-->
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          min-width="80"
          align="left"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.status | statusFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          min-width="160"
          align="left"
        />
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          min-width="150"
        >
          <template slot-scope="scope">
            <div>
              <el-button
                v-if="scope.row.status == 1"
                type="primary"
                size="small"
                style="margin-top: 10px"
                @click="online(scope.row)"
              >
                上架
              </el-button>
              <el-button
                v-if="scope.row.status == 2"
                type="primary"
                size="small"
                style="margin-top: 10px"
                @click="offline(scope.row)"
              >
                下架
              </el-button>
              <el-button
                type="primary"
                size="small"
                style="margin-top: 10px"
                @click="setPrice(scope.row, false)"
              >
                设置价格
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          background
          :current-page="searchParam.pageNo"
          :page-sizes="[15, 30, 50, 100, 200]"
          :page-size="searchParam.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalRows"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 设置价格 -->
      <el-dialog
        title="设置价格"
        :visible.sync="setPriceVisible"
        width="55%"
      >
        <!--            <el-row :gutter="30" class="row search" type="flex" style="margin-bottom:0;">-->
        <el-form
          ref="setPriceForm"
          :rules="setPriceRules"
          :model="setPriceForm"
          label-width="250px"
          label-suffix=":"
          label-position="right"
          size="mini"
          style="width: 100%"
        >
          <el-form-item
            label="问诊价格"
            class="required-label"
            prop="price"
          >
            <el-col :span="18">
              <el-input-number
                v-model="setPriceForm.price"
                size="small"
                :precision="2"
                :min="0"
                :max="9999"
                placeholder="请输入价格"
                @change="changePrice($event)"
              />
            </el-col>
          </el-form-item>

          <el-form-item
            label="接诊服务费结算方式（上级医生）"
            prop="commissionType"
          >
            <el-col :span="18">
              <el-radio-group
                v-model="setPriceForm.commissionType"
                size="small"
                style="line-height: 45px"
              >
                <div>
                  <el-radio
                    :label="1"
                    style="float: left; margin-top: 5px; line-height: 20px"
                  >
                    按比例分佣（%）
                  </el-radio>
                  <span
                    style="float: right; width: 100px"
                  ><el-input-number
                    v-model="setPriceForm.commissionPrice1"
                    size="small"
                    :precision="2"
                    :min="0"
                  /></span>
                </div>
                <div>
                  <el-radio
                    :label="2"
                    style="float: left; margin-top: 30px; line-height: 20px"
                  >
                    固定分佣金额（元）
                  </el-radio>
                  <span
                    style="float: right; width: 100px; margin-left: 14px"
                  ><el-input-number
                    v-model="setPriceForm.commissionPrice2"
                    size="small"
                    :precision="2"
                    :min="0"
                    :max="9999"
                  /></span>
                </div>
              </el-radio-group>
            </el-col>
          </el-form-item>
        </el-form>
        <!--            </el-row>-->
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="setPriceVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="confirmSetPrice"
          >确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  let vm = null;
  import {
    gteServiceType,
    doctorServiceSearch,
    setBatchUpdatePrice,
    updatePrice,
    batchUndeploy,
    doctorServiceDeploy,
    doctorServiceUndeploy,
    doctorServiceBatchDeploy,
    doctorServiceProfit,
  } from '@/api/serviceList';
  export default {
    data() {
      return {
        isUp: false,
        endFlag: false,
        beginFlag: false,
        loading: false,
        setPriceVisible: false,
        rangeTime: '',
        searchParam: {
          searchKey: '',
          serviceTypeId: 0,
          status: 0,
          startTime: '',
          endTime: '',
          pageSize: 15,
          pageNo: 1,
        },
        batchUpdatePriceFlag: false,
        setPriceForm: {
          commissionType: 1,
          commissionPrice: '',
          commissionPrice1: '',
          commissionPrice2: '',
          doctorId: '',
          serviceType: '',
          price: '',
        },
        timeSelect: [],
        diagnosisSelect: [],
        serviceTypeList: [],
        tableData: [],
        totalRows: 0,
        setPriceRules: {
          price: [{ required: true, message: '请输入问诊价格', trigger: 'blur' }],
          commissionType: [
            {
              required: true,
              message: '请选择接诊服务费结算方式',
              trigger: 'blur',
            },
          ],
        },
        liveBack: false,
        timeClickFlag: true,
        multipleSelection: [],
        tempPrice: 0,
        statusList: [
          {
            value: 0,
            label: '全部',
          },
          {
            value: 1,
            label: '下架',
          },
          {
            value: 2,
            label: '上架',
          },
        ],
        commissionTypeList: [
          {
            value: 0,
            label: '全部',
          },
          {
            value: 1,
            label: '按比例分佣',
          },
          {
            value: 2,
            label: '固定分佣',
          },
        ],
        profit: 0,
        selectedList: [],
        selectedPriceList: [],
        pickerOptions0: {
          disabledDate: (time) => {
            if (
              this.searchParam.endTimestamp != '' &&
              this.searchParam.endTimestamp != null
            ) {
              return (
                time.getTime() > new Date(this.searchParam.endTimestamp).getTime()
              );
            }
          },
        },
        pickerOptions1: {
          disabledDate: (time) => {
            return time.getTime() > new Date().getTime(); // 减去一天的时间代表可以选择同一天;
          },
        },
      };
    },
    mounted() {
      vm = this;
      this.getServiceTypeList();
      this.search();
    },
    methods: {
      selectToggle() {
        this.isUp = !this.isUp;
      },
      // 服务名称
      getServiceTypeList() {
        gteServiceType().then((res) => {
          if (res.code == '000000') {
            this.serviceTypeList = res.data;
          }
        });
      },

      search() {
        if (this.rangeTime) {
          this.searchParam.startTime = this.rangeTime[0];
          this.searchParam.endTime = this.rangeTime[1];
        } else {
          this.searchParam.startTime = '';
          this.searchParam.endTime = '';
        }
        this.loading = true;
        const params = this.searchParam;
        doctorServiceSearch(params).then((res) => {
          this.loading = false;
          if (res.code == '000000') {
            this.tableData = res.data.contentList;
            this.totalRows = res.data.total;
          }
        });
      },

      confirmSetPrice() {
        if (
          this.setPriceForm.price != 0 &&
          (this.setPriceForm.price == '' || this.setPriceForm.price == undefined)
        ) {
          this.$message({
            message: '请输入问诊价格',
            type: 'warning',
          });
          return;
        }
        if (
          this.setPriceForm.commissionType == null ||
          this.setPriceForm.commissionType == ''
        ) {
          this.$message({
            message: '请选择接诊服务费结算方式（上级医生）',
            type: 'warning',
          });
          return;
        }

        if (
          this.setPriceForm.commissionType == 1 &&
          this.setPriceForm.commissionPrice1 == undefined
        ) {
          this.$message({
            message: '请输入按比例分佣',
            type: 'warning',
          });
          return;
        } else if (
          this.setPriceForm.commissionType == 1 &&
          this.setPriceForm.commissionPrice1 > 100
        ) {
          this.$message({
            message: '请输入按比例分佣0-100',
            type: 'warning',
          });
          return;
        }
        if (
          this.setPriceForm.commissionType == 2 &&
          this.setPriceForm.commissionPrice2 == undefined
        ) {
          this.$message({
            message: '请输入固定分佣金额',
            type: 'warning',
          });
          return;
        }

        let timeoutId = null;
        timeoutId && clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
          this.clickHandle();
        }, 500);
      },
      // 防止按钮多次点击
      clickHandle() {
        this.$refs.setPriceForm.validate((valid) => {
          if (valid) {
            this.loading = true;
            // 批量设置价格
            if (this.batchUpdatePriceFlag) {
              const setPriceList = [];
              for (let i = 0; i < this.multipleSelection.length; i++) {
                if (this.setPriceForm.commissionType == 1) {
                  this.setPriceForm.commissionPriceStr =
                    this.setPriceForm.commissionPrice1;
                } else if (this.setPriceForm.commissionType == 2) {
                  this.setPriceForm.commissionPriceStr =
                    this.setPriceForm.commissionPrice2;
                }

                setPriceList.push({
                  doctorId: this.multipleSelection[i].doctorId,
                  serviceType: this.multipleSelection[i].serviceType,
                  price: this.setPriceForm.price,
                  commissionType: this.setPriceForm.commissionType,
                  commissionPriceStr: this.setPriceForm.commissionPriceStr,
                  commissionPrice: this.setPriceForm.commissionPriceStr,
                });
              }
              setBatchUpdatePrice(setPriceList).then((res) => {
                this.loading = false;
                if (res.code == '000000') {
                  this.$message({
                    message: '设置价格成功',
                    type: 'success',
                  });
                  this.setPriceVisible = false;
                  this.search();
                } else {
                  this.$message({
                    message: res.message,
                    type: 'error',
                  });
                }
              });
            } else {
              if (this.setPriceForm.commissionType == 1) {
                this.setPriceForm.commissionPriceStr =
                  this.setPriceForm.commissionPrice1;
              } else if (this.setPriceForm.commissionType == 2) {
                this.setPriceForm.commissionPriceStr =
                  this.setPriceForm.commissionPrice2;
              }
              this.setPriceForm.commissionPrice =
                this.setPriceForm.commissionPriceStr;
              updatePrice(this.setPriceForm).then((res) => {
                this.loading = false;
                if (res.code == '000000') {
                  this.$message({
                    message: '设置价格成功',
                    type: 'success',
                  });
                  this.setPriceVisible = false;
                  this.search();
                } else {
                  this.$message({
                    message: res.message,
                    type: 'error',
                  });
                }
              });
            }
          }
        });
      },
      handleSizeChange(value) {
        this.searchParam.pageSize = value;
        this.search();
      },
      handleCurrentChange(value) {
        this.searchParam.pageNo = value;
        this.search();
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      // 刷新页面
      refresh() {
        this.searchParam = {
          searchKey: '',
          serviceTypeId: 0,
          status: 0,
          startTime: '',
          endTime: '',
          pageSize: 15,
          pageNo: 1,
        };
        this.rangeTime = '';
        this.search();
      },
      // 批量下架
      batchOffline() {
        if (this.multipleSelection.length == 0) {
          this.$message({
            message: '请先选择要操作的数据',
            type: 'warning',
          });
          return;
        }
        this.setSelectedList();
        this.$confirm(
          '一旦下架将无法预约您的问诊，已预约的问诊不受影响，确定下架？',
          '确定下架问诊吗?',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
          batchUndeploy(this.selectedList).then((res) => {
            if (res.code == '000000') {
              this.$message({
                message: '下架成功',
                type: 'success',
              });
              this.search();
            } else {
              this.$message({
                message: res.message,
                type: 'error',
              });
            }
          });
        });
      },
      // 批量上架
      batchOnline() {
        if (this.multipleSelection.length == 0) {
          this.$message({
            message: '请先选择要操作的数据',
            type: 'warning',
          });
          return;
        }

        if (!this.setSelectedPriceList()) {
          return;
        }

        // this.setSelectedList();
        doctorServiceBatchDeploy(this.selectedPriceList).then((res) => {
          if (res.code == '000000') {
            this.$message({
              message: '上架成功',
              type: 'success',
            });
            this.search();
          } else {
            this.$message({
              message: res.message,
              type: 'error',
            });
          }
        });
      },
      // 批量设置价格
      batchSetPrice() {
        if (this.multipleSelection.length == 0) {
          this.$message({
            message: '请先选择要操作的数据',
            type: 'warning',
          });
          return;
        }
        // else {
        //   this.setSelectedPriceList();
        // }
        this.setPrice(this.multipleSelection[0], true);
      },
      setSelectedList() {
        if (this.multipleSelection.length > 0) {
          this.selectedList = [];
          for (let i = 0; i < this.multipleSelection.length; i++) {
            this.selectedList.push({
              doctorId: this.multipleSelection[i].doctorId,
              serviceType: this.multipleSelection[i].serviceType,
            });
          }
        }
      },
      setSelectedPriceList() {
        if (this.multipleSelection.length > 0) {
          this.selectedPriceList = [];
          for (let i = 0; i < this.multipleSelection.length; i++) {
            if (
              this.multipleSelection[i].price != 0 &&
              (this.multipleSelection[i].price == '' ||
                this.multipleSelection[i].price == null)
            ) {
              this.$message({
                message: '请先设置"问诊价格"',
                type: 'warning',
              });
              return false;
            }
            this.selectedPriceList.push({
              doctorId: this.multipleSelection[i].doctorId,
              serviceType: this.multipleSelection[i].serviceType,
              price: this.multipleSelection[i].price,
            });
          }
          return true;
        }
      },

      // 上架
      online(row) {
        if (row.price == null) {
          this.$message({
            message: '请先设置价格',
            type: 'warning',
          });
          return;
        }
        doctorServiceDeploy({
          doctorId: row.doctorId,
          serviceType: row.serviceType,
        }).then((res) => {
          if (res.code == '000000') {
            this.$message({
              message: '上架成功',
              type: 'success',
            });
            this.search();
          } else {
            this.$message({
              message: res.message,
              type: 'error',
            });
          }
        });
      },
      // 下架
      offline(row) {
        this.$confirm(
          '一旦下架将无法预约您的问诊，已预约的问诊不受影响，确定下架？',
          '确定下架问诊吗?',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).then(() => {
          doctorServiceUndeploy({
            doctorId: row.doctorId,
            serviceType: row.serviceType,
          }).then((res) => {
            if (res.code == '000000') {
              this.$message({
                message: '下架成功',
                type: 'success',
              });
              this.search();
            } else {
              this.$message({
                message: res.message,
                type: 'error',
              });
            }
          });
        });
      },
      setPrice(row, batchUpdatePriceFlag) {
        if (this.$refs.setPriceForm) {
          this.$refs.setPriceForm.resetFields();
        }
        this.batchUpdatePriceFlag = batchUpdatePriceFlag;
        this.setPriceForm.doctorId = row.doctorId;
        this.setPriceForm.serviceType = row.serviceType;
        this.setPriceForm.price = row.price;
        this.setPriceForm.commissionType = '';
        this.setPriceForm.commissionPrice1 = undefined;
        this.setPriceForm.commissionPrice2 = undefined;
        this.setPriceForm.commissionType = row.commissionType;
        if (this.setPriceForm.commissionType == 1) {
          this.setPriceForm.commissionPrice1 = row.commissionPriceStr;
        } else if (this.setPriceForm.commissionType == 2) {
          this.setPriceForm.commissionPrice2 = row.commissionPriceStr;
        }
        this.setPriceForm.price = row.price;
        this.setPriceVisible = true;
      },

      getProfit(row) {
        doctorServiceProfit({
          doctorId: row.doctorId,
          serviceType: row.serviceType,
        }).then((res) => {
          if (res.code == '000000') {
            vm.profit = res.data;
            if (
              vm.setPriceForm.price != 0 &&
              (vm.setPriceForm.price == '' || vm.setPriceForm.price == null)
            ) {
              this.tempPrice = '';
            } else {
              this.tempPrice = this.setPriceForm.price * this.profit;
            }
          } else {
            this.$message({
              message: res.message,
              type: 'error',
            });
          }
        });
      },
      changePrice(e) {
        if (
          this.setPriceForm.price != 0 &&
          (this.setPriceForm.price == '' || this.setPriceForm.price == undefined)
        ) {
          this.tempPrice = '';
        } else {
          this.tempPrice = this.setPriceForm.price * this.profit;
        }
      },
    },
  };
</script>
<style lang="scss" scoped>
.diagnosis-list-content {
  .select-content {
    margin-bottom: 10px;
    padding: 10px;
    background: #fff;
    overflow: hidden !important;
    .title {
      height: 50px;
      display: flex;
      justify-content: flex-start;
      align-items: center;
    }
    .select-bottom {
      height: 50px;
      cursor: pointer;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #0d9078;
    }
  }

  .component-content {
    padding: 10px;
    background: #fff;
    overflow: hidden !important;
    .title {
      margin-bottom: 30px;
    }
  }
}
.required-label .el-form-item__label::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
</style>
