<template>
  <div>
    <div class="borderless">
      <div class="customer-head">
        <div class="customer-back">
          <el-button type="danger" style="border: none;background: none;color: red" icon="el-icon-arrow-left"
            @click="backToList">返回列表
          </el-button>
        </div>
        <div class="add-customer-btn">
          <!--<el-button type="info" icon="el-icon-printer" size="small" @click.stop="openReport()">报表打印-->
          <!--</el-button>-->
            <el-button v-if="form.dispatchingWorkers == 2" type="warning" size="small" :disabled="option.disabled" @click="editCustomer(2)">
                撤销派工
            </el-button>
            <el-button v-else type="warning" size="small" :disabled="option.disabled && (form.dispatchingWorkers == 0 || form.dispatchingWorkers == 1)" @click="editCustomer(1)">
                派工
            </el-button>

          <el-button type="primary" size="small"
            class="el-button--small-yh"  :disabled="!option.disabled" @click.stop="openEdit">编辑
          </el-button>
          <el-button type="primary" size="small" :disabled="option.disabled" @click="editCustomer(0)">
            保存数据
          </el-button>
        </div>
      </div>
      <trade-card title="基础资料" style="margin-top: 60px" v-loading="loadingBtn">
        <avue-form ref="form" class="trading-form" v-model="form" :option="option">
          <template slot="corpId">
            <crop-select v-model="form.corpId" corpType="KH" :disabled="option.disabled"
              @getCorpData="getCorpData"></crop-select>
          </template>

            <template slot="maintenanceAmount">
                <el-input v-model="form.maintenanceAmount" type="number" disabled
                          placeholder="请输入" size="small" :controls="false" style="width:100%;"></el-input>
            </template>
        </avue-form>
      </trade-card>
      <trade-card title="维修项目" v-loading="loadingBtn">
        <avue-crud ref="crud" :option="optionList" :data="data" :table-loading="loading" @saveColumn="saveColumn"
          @resetColumn="resetColumn" :cell-style="cellStyle">
          <template slot="headerSerial">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click.stop="addRow"
              :disabled="option.disabled" circle></el-button>
          </template>

            <template slot="costName" slot-scope="{ row, index }">
                <el-input v-if="row.$cellEdit" v-model="row.costName"
                          placeholder="请输入" size="small" :controls="false" style="width:100%;"></el-input>
                <span v-else>{{ row.costName }}</span>
            </template>
            <template slot="amount" slot-scope="{ row, index }">
                <el-input v-if="row.$cellEdit" v-model="row.amount"
                                 placeholder="请输入" size="small" :controls="false" style="width:100%;"
                @blur="amountblur">
                </el-input>
                <span v-else>{{ row.amount }}</span>
            </template>
            <template slot="remarks" slot-scope="{ row, index }">
                <el-input v-if="row.$cellEdit" v-model="row.remarks"
                          placeholder="请输入" size="small" :controls="false" style="width:100%;"></el-input>
                <span v-else>{{ row.remarks }}</span>
            </template>

          <template slot="menu" slot-scope="{ row, index }">
            <el-button size="small" type="text" :disabled="option.disabled" @click="rowCell(row, index)">{{
                row.$cellEdit ? "保存" : "修改"
            }}</el-button>
            <el-button size="small" type="text" :disabled="option.disabled" @click="rowDel(row, index)">删除
            </el-button>
          </template>
        </avue-crud>
      </trade-card>

      <containerTitle title="上传附件"></containerTitle>
      <c-upload v-loading="loadingBtn" typeUpload="CD"
        deleteUrl="/api/blade-sales-part/maintenanceFiles/remove" :data="maintenanceFiles" display
        :enumerationValue="35.1"></c-upload>




      <dictbiz-dialog ref="dictbiz" title="添加单位" code="unit" parentId="1585962784498225154" @closed="getAllWorkDicts">
      </dictbiz-dialog>

      <report-dialog :switchDialog="switchDialog" :reportId="form.id" reportName="配件系统-采购单" @onClose="onClose()">
      </report-dialog>


    </div>
  </div>
</template>

<script>
import { optionList } from "./js/optionList";
import reportDialog from "@/components/report-dialog/main";
import { multiply, sum, subtract } from "@/util/calculate";
import {getList as yhgetList} from "@/api/system/user";

import {
    maintenanceDetail,
    maintenanceDispatchingWorkers,
    maintenanceFeesRemove, maintenanceRevokeDispatchingWorkers,
    maintenanceSubmit
} from "@/api/basicData/maintenanceQ";
import { getGoodstype } from "@/api/basicData/product";
import { getList as CPgetList } from "@/api/basicData/product";
export default {
  name: "index",
  data() {
    return {
      switchDialog: false,
      loadingBtn: false,
      addressTitle: null,
      form: {},
      form2: {
      },
      form3: {

      },
      data: [],

      option: {
        menuBtn: false,
        labelWidth: 90,
        disabled: false,
        column: [
          {
            label: "客户名称",
            prop: "corpId",
            rules: [
              {
                required: true,
                message: "",
                trigger: "blur"
              }
            ],
            span: 16,

          },
            {
                label: "客户电话",
                prop: "corpTel",
                span: 8,
                rules: [
                    {
                        required: true,
                        message: "",
                        trigger: "blur"
                    }
                ],
            },
            {
                label: "设备名称",
                prop: "deviceId",
                dicData:[],
                dataType: "string",
                type: "select",
                props: {
                    label: 'cname',
                    value: 'id'
                },
                rules: [
                    {
                        required: true,
                        message: "",
                        trigger: "blur"
                    }
                ],
                span: 12,
                change: (val) => {
                    val.column.dicData.map(item=>{
                        if (val.value == item.id){
                            this.form.deviceName = item.cname
                        }
                    })
                },
            },
            {
                label: "设备地址",
                prop: "deviceAddress",
                dicData:[],
                dataType: "string",
                type: "cascader",
                props: {
                    label: 'name',
                    value: 'name'
                },
                filterable: true,
                minWidth: 250,
                span: 12,
                rules: [
                    {
                        required: true,
                        message: "",
                        trigger: "blur"
                    }
                ],
            },
            {
                label: "故障描述",
                prop: "faultDescribe",
                type: "textarea",
                minRows: 3,
                span: 24,
            },
            {
                label: "维修工名称",
                prop: "maintenanceWorkerId",
                dicData:[],
                dataType: "string",
                type: "select",
                props: {
                    label: 'name',
                    value: 'id'
                },
                rules: [
                    {
                        required: true,
                        message: "",
                        trigger: "blur"
                    }
                ],
                span: 8,
                change: (val) => {
                    val.column.dicData.map(item=>{
                        if (val.value == item.id){
                            this.form.maintenanceWorkerName = item.name
                        }
                    })
                },
            },
            {
                label: "维修工电话",
                prop: "maintenanceWorkerTel",
                span: 8,
                rules: [
                    {
                        required: true,
                        message: "",
                        trigger: "blur"
                    }
                ],
            },
            {
                label: "维修金额",
                prop: "maintenanceAmount",
                disabled:true,
                span: 8,
                type: "number",
            },
          {
            label: "报修日期",
            prop: "repairReportDate",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd 00:00:00",
            span: 8,
          },
            {
                label: "状态",
                prop: "status",
                dataType: "string",
                type: "select",
                disabled:true,
                dicUrl: "/api/blade-system/dict-biz/dictionary?code=state_Q",
                props: {
                    label: "dictValue",
                    value: "dictKey"
                },
                span: 8,
            },
          {
            label: "备注",
            prop: "remarks",
            type: "textarea",
            minRows: 3,
            span: 16,
          }
        ]
      },
        // 商品信息列表配置
      optionList: {},
        // 商品产品下拉数据
      goodsoptions: [],
        // 附件
        maintenanceFiles: [],
        loading:false,
    };
  },
  props: {
    detailData: {
      type: Object
    }
  },
  components: {
    reportDialog
  },

  async created() {
    this.optionList = optionList
      // 获取字典数据
      this.getAllWorkDicts()
      // 查看是否要id调用详情
    if (this.detailData.id) {
        this.option.disabled = true
      this.getDetail(this.detailData.id);
    }
    if (this.detailData.status == 1) {
      this.option.disabled = true;
    }

  },
  methods: {
      // 打印报表按钮事件
    openReport() {
      this.switchDialog = !this.switchDialog;
    },
    onClose(val) {
      this.switchDialog = val;
    },
      // 获取下拉字典
    getAllWorkDicts() {
        // 获取地址信息
        this.findObject(this.option.column, "deviceAddress").dicData = JSON.parse(localStorage.getItem('areaTypeTree'))
        // 获取维修工信息
        yhgetList().then(res=>{
            this.findObject(this.option.column, "maintenanceWorkerId").dicData = res.data.data.records
        })
        CPgetList().then(res=>{
            this.findObject(this.option.column, "deviceId").dicData = res.data.data.records
        })
    },
    cellStyle() {
      return "padding:0;height:40px;";
    },
      // 维修项目的失焦事件
      amountblur(){
        let sum = 0
        this.data.map(item=>{
            sum += Number(item.amount)
        })
        this.form.maintenanceAmount = sum
      },

    amountChange() {
      let val = 0
      this.data.forEach(e => {
        val = sum(val, e.amount)
        this.form.purchaseAmount = val
        this.form.orderAmount = subtract(this.form.purchaseAmount, this.form.thisUsedProfit)
      })
    },
    // countChange(row) {
    //   row.amount = multiply(row.price, row.storageInQuantity)
    //   row.storageAmount = multiply(row.purchaseAmount, row.storageInQuantity)
    //   let val = 0
    //   this.data.forEach(e => {
    //     val = sum(val, e.amount)
    //     this.form.purchaseAmount = val
    //     this.form.orderAmount = subtract(this.form.purchaseAmount, this.form.thisUsedProfit)
    //   })
    // },
      // 获取详情数据
    getDetail(id) {
      this.loadingBtn = true
        maintenanceDetail({ id: id })
        .then(res => {
          this.form = res.data.data;
          this.data = res.data.data.maintenanceFees;
          this.maintenanceFiles = res.data.data.maintenanceFiles ? res.data.data.maintenanceFiles : [];
        })
        .finally(() => {
          this.loadingBtn = false;
        });
    },
      // 客户下拉框
    getCorpData(row) {
      if (row) {
        this.form.corpName = row.cname
        this.form.corpTel = row.tel
      } else {
        this.form.corpName = null
        this.form.corpTel = null
      }
    },

    addRow() {
        // this.data.push({ $cellEdit: true, storageId: this.form.storageId })
       this.$refs["form"].validate((valid, done) => {
          done();
          if (valid) {
             this.data.push({ $cellEdit: true, storageId: this.form.storageId })
          } else {
             return false;
          }
       });
    },
    rowCell(row, index) {
        if (!row.costName) {
            return this.$message.warning('维修项目不能为空');
        }
        if (!row.amount) {
            return this.$message.warning('金额不能我空');
        }
      if (row.$cellEdit == true) {
        this.$set(row, "$cellEdit", false);
      } else {
        this.$set(row, "$cellEdit", true);
      }
    },
      // 费用删除
    rowDel(row, index) {
      this.$confirm("确定删除数据?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (row.id) {
          maintenanceFeesRemove({ids:row.id}).then(res => {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.data.splice(index, 1);
          });
        } else {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.data.splice(index, 1);
        }
        this.amountblur()
      });
    },
    //修改提交触发1 派工2 撤销派工3
    editCustomer(index) {
      this.$refs["form"].validate((valid, done) => {
        done();
        if (valid) {
          if (this.data.length == 0) {
            return this.$message.error('请添加一条维修项目');
          }
            let arr = this.data.map(item=>{
                return {
                    id:item.id?item.id:null,
                    costId:item.costId?item.costId:null,
                    costName:item.costName,
                    amount:item.amount,
                    number:1,
                    price:item.amount,
                    currency:'CNY',
                    settlementAmount:item.settlementAmount?item.settlementAmount:0,
                    remarks:item.remarks
                }
            })
            let list = this.maintenanceFiles.map(item=>{
                item.sort = 1
                return item
            })
            const obj = {
                id:this.form.id?this.form.id:null,
                sysNo:this.form.sysNo?this.form.sysNo:null,
                deviceId:this.form.deviceId,
                deviceName:this.form.deviceName,
                corpId:this.form.corpId,
                corpName:this.form.corpName,
                corpTel:this.form.corpTel,
                deviceAddress:this.form.deviceAddress,
                faultDescribe:this.form.faultDescribe,
                maintenanceWorkerId:this.form.maintenanceWorkerId,
                maintenanceWorkerName:this.form.maintenanceWorkerName,
                maintenanceWorkerTel:this.form.maintenanceWorkerTel,
                maintenanceAmount:this.form.maintenanceAmount,
                repairReportDate:this.form.repairReportDate,
                settlementAmount:this.form.settlementAmount?this.form.settlementAmount:0,
                remarks:this.form.remarks,
                status:this.form.status,
                maintenanceFees:arr,
                maintenanceFiles:list
            }
            this.loadingBtn = true;

            this.maintenanceSubmitfun(obj,index)
        } else {
          return false;
        }
      });
    },
      // 派工接口
      maintenanceDispatchingWorkersfun(obj){
          maintenanceDispatchingWorkers(obj).then(res=>{
              this.$message.success("派工成功");
              this.form = res.data.data;
              this.data = res.data.data.maintenanceFees;
              this.maintenanceFiles = res.data.data.maintenanceFiles ? res.data.data.maintenanceFiles : [];
              this.option.disabled = true;
          })
      },
      // 撤销派工
      maintenanceRevokeDispatchingWorkersfun(obj){
          maintenanceRevokeDispatchingWorkers(obj).then(res=>{
              this.$message.success("撤销派工成功");
              this.form = res.data.data;
              this.data = res.data.data.maintenanceFees;
              this.maintenanceFiles = res.data.data.maintenanceFiles ? res.data.data.maintenanceFiles : [];
              this.option.disabled = true;
          })
      },
      // 保存接口
      maintenanceSubmitfun(obj,index){
          maintenanceSubmit(obj).then(res => {
              this.form = res.data.data;
              // this.data = res.data.data.maintenanceFees;
              // this.maintenanceFiles = res.data.data.maintenanceFiles ? res.data.data.maintenanceFiles : [];
              this.detailData.status = 1
              this.option.disabled = true;

              if (index == 0) {
                  this.$message.success("保存成功");
                  this.getDetail(this.form.id)
              }else if (index == 1) {
                  this.maintenanceDispatchingWorkersfun(obj)
              }else if (index == 2) {
                  this.maintenanceRevokeDispatchingWorkersfun(obj)
              }else {}
              this.$refs.crud.refreshTable();
          }).finally(() => {
              this.loadingBtn = false;
          });
      },

    async saveColumn() {
      const inSave = optionList
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    async resetColumn() {
      this.optionList = optionList;
      const inSave = optionList
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        this.getAllWorkDicts()
        this.$message.success("重置成功");
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    openEdit() {
      // this.detailData.status = 2
        this.option.disabled = false
      // this.option = this.$options.data().option;
      // this.$refs.crud.refreshTable();
    },
    //返回列表
    backToList() {
      this.$emit("goBack");
    },

  },
  watch: {
    // data: function (rows) {
    //   let val = 0
    //   rows.forEach(e => {
    //     val = sum(val, e.amount)
    //     this.form.purchaseAmount = val
    //     this.form.orderAmount = subtract(this.form.purchaseAmount, this.form.thisUsedProfit)
    //   })
    // }
  }
};
</script>

<style lang="scss" scoped>
.trading-form ::v-deep .el-form-item {
  margin-bottom: 8px !important;
}

::v-deep .el-dialog__body {
  padding: 0px 20px 15px 20px;
}

::v-deep .el-form-item__error {
  display: none !important;
}

.img-form ::v-deep .el-form-item {
  height: 150px;
  line-height: 150px;
  margin-bottom: 8px !important;
}

.img-form ::v-deep .avue-upload__icon {
  font-size: 20px;
  width: 150px;
  height: 150px;
  line-height: 150px;
}

::v-deep .el-table .cell {
  padding: 0 2px !important;
}

::v-deep .avue-crud .el-table .el-form-item__label {
  left: -1px;
}

.addressTabs {
  display: flex;
  justify-content: center;

  span {
    width: 100px;
    font-size: 18px;
    font-weight: 600;
    text-align: center;
  }
}
</style>
